I have a custom exception class annotated to return a given HttpStatus
:
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason=\"Invalid parameter\")
The correct way is to introduce exception handler in your controller, then you can set response body of any status code:
@Controller
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class SomeController {
...
@ExceptionHandler(BadRequestException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody
Map handleIndexNotFoundException(BadRequestException bre,
HttpServletRequest request, HttpServletResponse resp) {
HashMap result = new HashMap<>();
result.put("error", true);
result.put("error_message", bre.getMessage());
return result;
}
}
Move over you don't have to pollute your model/exception classes with any Spring Web MVC annotations and dependency.
If you want to share the handler with all controller look into @ControllerAdvice.