I use @ExceptionHandler to handle exceptions thrown by my web app, in my case my app returns JSON response with HTTP status for error
public final class ResourceNotFoundException extends RuntimeException {
}
@ControllerAdvice
public class AppExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleNotFound() {
return "404";
}
}
Just define an Exception, an ExceptionHandler, throw the Exception from your business code controller.