-1

Is there at spring boot a configuration possible, which returns all errors in a json format?

For example 404, or 401. Need to replace this 404 page with just json.

enter image description here

Many thanks

Gimhani
  • 1,318
  • 13
  • 23
J. S
  • 29
  • 2
  • 1
    you mean the error responses for rest calls or ..? Just elaborate on your problem more. – Gimhani Sep 03 '18 at 12:39
  • @Gimhani yes, it there is a rest call, and it ends before my method then it throws a error in HTML format, is there a config for json format? – J. S Sep 03 '18 at 12:50
  • is this the problem you are facing?https://stackoverflow.com/questions/50602291/spring-error-response-auto-converted-to-html-from-json – Gimhani Sep 03 '18 at 14:31
  • can you add the code segment for receiving the response? – Gimhani Sep 03 '18 at 14:46
  • @Gimhani no, there is no code, if you make a call to a resource who not exist – J. S Sep 03 '18 at 15:29
  • Maybe this? https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html – ndrone Sep 03 '18 at 16:00

3 Answers3

1

This is since by default, springboot produces the error as html. To get the Json output, add produces argument as follows so that the content returned will be for sure in json format.

@RequestMapping(....., produces = "application/json")
Gimhani
  • 1,318
  • 13
  • 23
  • no, sorry not my controllers , the default mapping of the spring boot – – J. S Sep 03 '18 at 15:28
  • @J.S see if this solves your problem https://stackoverflow.com/questions/25356781/spring-boot-remove-whitelabel-error-page – Gimhani Sep 04 '18 at 02:34
1

You can custom your error controller to handle it:

@RestController
public class CustomErrorController extends BasicErrorController {
private final Logger logger = LoggerFactory.getLogger(CustomErrorController.class);

public CustomErrorController(ErrorAttributes errorAttributes) {
    super(errorAttributes, new ErrorProperties());
}

// let all MediaType return json data
@RequestMapping(consumes = MediaType.ALL_VALUE)
public ResponseEntity<Map<String, Object>> allError(HttpServletRequest request, HttpServletResponse response) {
    return super.error(request);
}
}
ZUZI
  • 11
  • 1
0

You mean using @ControllerAdvice with the content header set to application/json

ndrone
  • 3,524
  • 2
  • 23
  • 37