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;
}
}
本文详细介绍了SpringBoot错误页面的处理机制,包括默认状态下的错误展示和自定义错误响应。自定义错误页面可以通过在templates下放置`error/状态码.html`或设置通用的`4xx.html`、`5xx.html`来实现。同时,通过定义异常处理器和自定义异常类可以定制JSON数据返回,结合`@ControllerAdvice`和`@ExceptionHandler`注解处理特定异常,并使用`forward:/error`进行转发。此外,还可以通过扩展`DefaultErrorAttributes`来自定义返回的JSON数据内容。
644

被折叠的 条评论
为什么被折叠?



