1.自定义异常
/**
* @Auther: DELL
* @Date: 2020/3/12 14:00
* @Description:
*/
public class myException extends RuntimeException {
public myException() {
super("用户不在场");
}
}
2.首先自定义处理器
/**1..................
* @ExceptionHandler 可以指定class如果不指定就是处理所有的
* @param e
* @return
* 这种情况下游览器和服务器返回的都是json
*/
@ExceptionHandler(myException.class)
public String myexcptionC(Exception e, HttpServletRequest request){
Map<String,Object> Object=new HashMap<>();
//必须传入自己的错误状态码
request.setAttribute("javax.servlet.error.status_code",500);
Object.put("code","user don't have ");
Object.put("message",e.getMessage());
request.setAttribute("ext",Object);
return "forward:/error";
}
3.给容器中加入我们自己定义的ErrorAttributes
2.2.5版本和1.X在这里有区别
首先如果我们不加这个构造器的话,就会显示的时候exception为空。
其次2.2.5这里讲RequestAttributes换成了WebRequest。
/**
* @Auther: DELL
* @Date: 2020/3/12 15:43
* @Description:
*/
@Component
public class myErrorAttributes extends DefaultErrorAttributes {
public myErrorAttributes() {
super(true);
}
//返回值的map就是页面和json能获取的所有字段
@Override
public Map<String, Object> getErrorAttributes(WebRequest requestAttributes, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes( requestAttributes, includeStackTrace);
map.put("company","atguigu");
//我们的异常处理器携带的数据
Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
map.put("ext",ext);
return map;
}
}