typora-root-url: 学习图片
springboot错误页面的处理机制
1.默认状态下:
*页面:
*json数据:
2.如何定制错误响应:
原理参照(ErrorMvcAutoConfiguration)
a.DefaultErrorAttributes:
b.BasicErrorController
c.errorPageCustomizer 错误页面响应
d.DefaultErrorViewResolver
步骤:
系统出现4xx 5xx之类的错误,errorPageCustomizer就会生效,就会来到/errro请求,然后通过BasicErrorController处理返回json或者html数据;响应页面是DefaultErrorViewResolver决定的(通过error/状态码 响应)。
1.如何定制错误页面
a.有模板引擎情况下:error/状态码.html放在templates下,没有模板引擎,放在静态资源下。
b.4xx.html或者5xx.html来适配其他的错误
c.页面能获取的信息
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2>
</main>
2如何定制json数据
a.做一个定制的异常机制
package com.liu.springboot_demo.exception;
public class UserNotExistException extends RuntimeException {
public UserNotExistException() {
super("用户不存在");
}
}
b.定义异常处理器
package com.liu.springboot_demo.handler;
import com.liu.springboot_demo.exception.UserNotExistException;
import com.sun.deploy.net.HttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(UserNotExistException.class)
public String handlerException(Exception e, HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
map.put("code","user.notexist");
map.put("msg","用户不存在5555");
request.setAttribute("ext",map);
//修改状态码
request.setAttribute("javax.servlet.error.status_code",500);
//转发到error页面,让它自己适配返回json还是html
return "forward:/error";
}
}
c自定义定义返回的json数据
package com.liu.springboot_demo.handler;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.stereotype.Component;;
import org.springframework.web.context.request.WebRequest;
import java.util.Map;
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
public Map<String, Object> getErrorAttributes(WebRequest requestAttributes, boolean includeStackTrace) {
Map<String,Object> errormap= super.getErrorAttributes(requestAttributes, includeStackTrace);
Map<String,Object> map = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
errormap.put("tag","刘");
errormap.put("ext",map);
return errormap;
}
}