1、@ExceptionHandler
spring MVC 中的@ExceptionHandler可以对web的服务器端运行错误, 做统一的处理,使得http status code 从原本的500改成200,(状态码500--服务器遇到未知错误,导致无法完成客户端当前请求,200--服务器已成功接收并将处理结果返回给客户端)并去执行用@ExceptionHandler注解的方法。 前提是实现了这个方法的Class被那个访问的Controller 继承了。
//错误
@RequestMapping("/admin")
@ResponseBody
public String admin(@RequestParam(value="key",required=false) String key){
if("admin".equals(key)){
return "hello admin";
}else{
throw new IllegalArgumentException("key 错误");
}
}
//处理错误
@ExceptionHandler
@ResponseBody
public String error(Exception e){
return "error:"+e.getMessage();
}
2/