A possible way to do something like this is to use the @ExceptionHandler
annotation to create a handler method inside your controller.
@RestController
@RequestMapping(produces = APPLICATION_JSON_VALUE)
public class MyController {
@RequestMapping(value = "/find", method = GET)
public Object find() {
throw new UnsupportedOperationException("Not implemented yet!");
}
@ExceptionHandler
public ErrorListModel handleException(Exception exception) {
ExceptionModel exceptionModel = new ExceptionModel(1337, exception.getMessage());
ErrorListModel list = new ErrorListModel();
list.add(exceptionModel);
return list;
}
private class ErrorListModel {
private List<ExceptionModel> errors = new ArrayList<>();
public void add(ExceptionModel exception) {
errors.add(exception);
}
public List<ExceptionModel> getErrors() {
return errors;
}
}
private class ExceptionModel {
private int code;
private String message;
public ExceptionModel(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
}
The private classes ErrorListModel
and ExceptionModel
just help defining how the resulting JSON body should look, and I assume you already have your own, similar classes.
The find
method just throws an exception for us to handle, which gets intercepted by the handleException
method because it's annotated with @ExceptionHandler
. In here, we create an ExceptionModel
, populate it with information from the original exception, and add it to an ErrorListModel
, which we then return.
This blog post from 2013 explains the features better than I ever could, and it also mentions an additional option, @ControllerAdvice
. It basically allows you to re-use the exception handling in other controllers as well.