quarks
quarks

Reputation: 35276

JSON-type Error response handler for Spring controller

I have this exception handler which works just fine:

@ExceptionHandler(DataNotExistException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Data not exist")
public void handleDataNotExistException() {

}

I need to put this exception handler to the exception will not be shown in the browser. Although it works, it shows the "generic" Jetty Browser error codes. I need to have a JSON-type response type.

I tried returning a Class-type error but the exception shows in the browser. I am thinking of using a Map.

Upvotes: 1

Views: 393

Answers (1)

Luciano
Luciano

Reputation: 8582

If your request contains the header Accept=application/json then annotate your method with @ResponseBody and return the object that will be transformed to json. Remove the reason from @ResponseStatus.

Upvotes: 1

Related Questions