带有@ResponseStatus注解的异常类会被ResponseStatusExceptionResolver 解析。
可以实现自定义的一些异常,同时在页面上进行显示。具体的使用方法如下:
1.首先定义一个异常类:
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "用户名和密码不匹配!")
public class UserNameNotMatchPasswordException extends RuntimeException{
}
2.人为抛出一个异常:
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
if (i==13){
throw new UserNameNotMatchPasswordException();
}
System.out.println("testResponseStatusExceptionResolver....");
return "success";
}
3.输入如下额路径:
http://localhost:8090/testResponseStatusExceptionResolver?i=13
当然,也可以在方法上进行修饰:
@ResponseStatus(reason = "测试",value = HttpStatus.NOT_FOUND)
@RequestMapping("/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
if (i==13){
throw new UserNameNotMatchPasswordException();
}
System.out.println("testResponseStatusExceptionResolver....");
return "success";
}
这时所有的请求都会报错。