发表于: 2017-09-05 20:04:25
2 956
今天:
Spring MVC处理异常(注解):
@ResponseStatus的两种用法:
1.注解在自定义的异常类上面,当此异常在controller中被抛出时,直接返回HTTP状态码。
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such order")
public class OrderNotFoundException extends RuntimeException {
public OrderNotFoundException(String orderId) {
super(orderId + " not found");
}
}
可以在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";
}
2.和@ExceptionHandler配合起来,注解在controller上,不需要自定义异常(方法里就什么都不用写了)
@ResponseStatus(value=HttpStatus.CONFLICT,
reason="Data integrity violation") // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void conflict() {
// Nothing to do
}
如果使用JSP页面,可以将异常信息隐藏在页面源文件中:
<h1>Error Page</h1>
<p>Application has encountered an error. Please contact support on ...</p>
<!--
Failed URL: ${url}
Exception: ${exception.message}
<c:forEach items="${exception.stackTrace}" var="ste"> ${ste}
</c:forEach>
-->
@ExceptionHandler:
括号中是需要捕获的异常的类,多个用逗号隔开
@ExceptionHandler({SQLException.class,DataAccessException.class})
public String databaseError() {
// Nothing to do. Returns the logical view name of an error page, passed
// to the view-resolver(s) in usual way.
// Note that the exception is NOT available to this view (it is not added
// to the model) but see "Extending ExceptionHandlerExceptionResolver"
// below.
return "databaseError";
}
@ExceptionHandler标注的方法不能返回Model,只能返回ModelAndView。(不知道为什么)
@ExceptionHandler只对当前controller有效!
@ControllerAdvice用于全局控制异常的捕获。注解在类上。
把上面方法都结合起来:
@ControllerAdvice
class 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;
}
}
在RESTful工程中,同时返回HTTP状态码和错误信息JSON(实用一些):
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MyBadDataException.class)
@ResponseBody ErrorInfo handleBadRequest(HttpServletRequest req, Exception ex) {
return new ErrorInfo(req.getRequestURL(), ex);
}
明天:不知道
总结:无
进度:无
问题:无
评论