Spring ControllerAdvice how to return Json or html page according to Accept request header?

Viewed 107

Now, App can return a cutstom 404 page.

@ControllerAdvice
class GlobalControllerExceptionHandler {

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public String handle404(WebRequest request) {
        return "/exceptions/404";
    }

}

And I wonder how should I do, if I want to get a JSON when Accept request header is Accept: application/json, like this:

$> curl -H "Accept: application/json" http://localhost:8080/no-such-page

{"timestamp":"2018-04-11T05:56:03.845+0000","status":404,"error":"Not Found","message":"No message available","path":"/no-such-page"}```
0 Answers
Related