在我们自定义的异常上使用ResponseStatus注解。当我们的Controller抛出异常,并且没有被处理的时候,他将返回HTTP STATUS 为指定值的 HTTP RESPONSE,比如:@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")// 404public class OrderNotFoundException extends RuntimeException {// ...}我们的Controller为: @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";}这时候会返回404,转到404页面而不是错误页面
Controller Based Exception Handling
在一个Controller中,,注意这种只在单个Controller中有效。这么做可以:
发生异常后,改变Response status,一般而言,发生异常返回HTTP STATUS 500.我们可以变为其他。
在类上使用 @ControllerAdvice注解,可以使得我们处理整个程序中抛出的异常。。 举例:class GlobalControllerExceptionHandler {@ResponseStatus(HttpStatus.CONFLICT)// 409@ExceptionHandler(DataIntegrityViolationException.class)public void handleConflict() {// Nothing to do} //转到特定页面 。。。。。}如果我们要处理程序中所有的异常可以这么做:@ControllerAdviceclass GlobalDefaultExceptionHandler {public static final String DEFAULT_ERROR_VIEW = "error";@ExceptionHandler(value = Exception.class)public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {// If the exception is annotated with @ResponseStatus rethrow it and let// the framework handle it - like the OrderNotFoundException example// at the start of this post.// AnnotationUtils is a Spring Framework utility class.if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {throw e;}// Otherwise setup and send the user to a default error-view.ModelAndView mav = new ModelAndView();mav.addObject("exception", e);mav.addObject("url", req.getRequestURL());mav.setViewName(DEFAULT_ERROR_VIEW);return mav;}}