十一(二)、springMVC之异常处理ResponseStatusExceptionResource&DefaultHandlerExceptionResplver


承接上文:

ResponseStatusExceptionResource :

更改自定义异常的状态码和异常原因

目录结构

自定义异常:SelfDefineException.java

 1 package handler;
 2 
 3 import org.springframework.http.HttpStatus;
 4 import org.springframework.web.bind.annotation.ResponseStatus;
 5 
 6 /**
 7  * 自定义 HTTP状态码和 理由 
8 * 使用时 可以把@ControllerAdvice 注释掉看效果 9 * 10 * @author lixiuming 11 * 12 */ 13 @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "用户名密码不匹配") 14 public class SelfDefineException extends RuntimeException { 15 16 /** 17 * 18 */ 19 private static final long serialVersionUID = -4891787694631373363L; 20 21 }

测试类EceptionController.java:

自定义异常中的注解@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "用户名密码不匹配")也可以放在testResponseStatusExceptionResource方法上,也可更改状态码;

 1 package handler;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RequestParam;
 6 
 7 @RequestMapping("/emp")
 8 @Controller
 9 public class EceptionController {
10 
11     @RequestMapping("/testResponseStatusExceptionResource")
12     public String testResponseStatusExceptionResource(@RequestParam("i") int i) {
13         if (i == 13) {
14             throw new SelfDefineException();
15         }
16         System.out.println("testResponseStatusExceptionResource");
17         return "success";
18     }
19 }

运行结果:

访问http://localhost:8080/DataOperate/emp/testResponseStatusExceptionResource?i=13,跳转到error页面,且控制台打印错误消息;

DefaultHandlerExceptionResplver :

对一些特殊的异常进行了处理,比如:

  • NoSuchRequestHandlingMethodException??
  • HttpReques tMethodNotSupportedException??
  • HttpMediaTypeNotSuppo rtedException??
  • HttpMediaTypeNotAcceptableException ??