16、SpringBoot-CRUD错误处理机制(3)

 3)、将自己指定的数据携带出去

出现错误以后,会来到/error请求,会被BasicErrorController 进行处理
响应出去的数据是由 getErrorAttributes 得到的( AbstractErrorController的方法)
protected Map<String, Object> getErrorAttributes(HttpServletRequest request,
     boolean includeStackTrace) { WebRequest webRequest
= new ServletWebRequest(request); return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace); }

 

 

3.1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中
 
3.2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到
        容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;
public abstract class AbstractErrorController implements ErrorController {
    private final ErrorAttributes errorAttributes;
...
}

 

 此时自定义的错误代码中的字段并没有显示

//给容器中加入
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest,
                                                  boolean includeStackTrace) {
        Map<String, Object> map =super.getErrorAttributes(webRequest,includeStackTrace);
        map.put("user","user...");
        return map;
    }
}

 

 

错误页面:

 

 自定义异常的字段

@ControllerAdvice
public class MyException  {
    @ExceptionHandler(UserException.class)
    public String userExc(Exception e, HttpServletRequest request){
        Map<Object,String> map = new HashMap<>();

        //传入我们自己的错误状态码  4xx  5xx
        /**
         * Integer statusCode = (Integer) request
         .getAttribute("javax.servlet.error.status_code");
         */
        request.setAttribute("javax.servlet.error.status_code",500);

        map.put("code","user.not.exist");
        map.put("message","mymessage");
        request.setAttribute("exc",map);

        return "forward:/error";
    }
}
//给容器中加入
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

    //返回的值map就是页面和json能获取的所有字段
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest,
                                                  boolean includeStackTrace) {

        Map<String, Object> map =super.getErrorAttributes(webRequest,includeStackTrace);

        map.put("user","user...");

        //自己的异常处理器携带的数据
        //0 是request中
        //1 是session中
        Map<String, Object> exc = (Map<String, Object>) webRequest.getAttribute("exc", 0);

        map.put("exc",exc);
        return map;
    }
}

 

 错误的页面:

<h1>status:[[${status}]]</h1>
<h1>timestamp:[[${timestamp}]]</h1>
<h1>error:[[${error}]]</h1>
<h1>message:[[${message}]]</h1>
<h1>user:[[${user}]]</h1>
<h1>exc.code:[[${exc.code}]]</h1>
<h1>exc.message:[[${exc.message}]]</h1>

 

 

 

posted @ 2019-02-09 00:11  MrChengs  阅读(250)  评论(0编辑  收藏  举报