Spring Exception Handling:
--------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------
Using HTTP Status Codes
Normally any unhandled exception thrown when processing a web-request causes the server to return an HTTP 500 response. However, any exception that you write yourself can be annotated with the
@ResponseStatus
annotation (which supports all the HTTP status codes defined by the HTTP specification). When an annotated exception is thrown from a controller method, and not handled elsewhere, it will automatically cause the appropriate HTTP response to be returned with the specified status-code.
For example, here is an exception for a missing order.
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order") // 404
public class OrderNotFoundException extends RuntimeException {
// ...
}
And here is a controller method using it:
@RequestMapping(value="/orders/{id}", method=GET)
public String showOrder(@PathVariable("id") long id, Model model) {
Order order = orderRepository.findOrderById(id);
if (order == null) throw new OrderNotFoundException(id);
model.addAttribute(order);
return "orderDetail";
}
A familiar HTTP 404 response will be returned if the URL handled by this method includes an unknown order id.
Controller Based Exception Handling
Using @ExceptionHandler
You can add extra (
@ExceptionHandler
) methods to any controller to specifically handle exceptions thrown by request handling (@RequestMapping
) methods in the same controller. Such methods can:- Handle exceptions without the
@ResponseStatus
annotation (typically predefined exceptions that you didn’t write) - Redirect the user to a dedicated error view
- Build a totally custom error response
No comments:
Post a Comment