如何配置springboot错误页,配置全局异常

2025-05-06 17:13:24

1、错误页绝对是所有的web项目之中必须具有的一项信息显示处理,但是在传统的web项目开发之中,错误页都是在web.xml文件之中进行配置的,不过遗憾的时候springboot之中并不存在web.xml配置文件这一项,那么如果要想进行错误页的处理,最好的做法是需要根据每一个错误代码创建一个属于自己的错误显示页。1、所有的错误页都是普通的静态文件,那么建议在"src/main/view/static"目录下创建几个常见的错误页(常见的错误的HTTP返回编码:404、500).

如何配置springboot错误页,配置全局异常

3、那么此时只要出现了错误,就会找到相应的http状态码,而后跳转到指定的错误路径上进行显示。

如何配置springboot错误页,配置全局异常

5、如果此时配置有错误页,那么这个时候错误会同意跳转到500所在的路径下进行错误的显示,但是如果说现在希望能够显示出错误更加详细的内容呢?

如何配置springboot错误页,配置全局异常

7、定义error.html页面:<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"> <head> <title>SpringBoot模板渲染</title> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> </head><body> <p th:text="${url}" /> <p th:text="${exception.message}" /></body></html>

如何配置springboot错误页,配置全局异常

8、对于全局异常信息显示除了采用以上的跳转处理方式之外,孀晏弁钾也可以做的简单一些,使用Rest进行显示:package com.gwolf.advice;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;@RestControllerAdvice //作为一个控制层的切面处理public class GlobalExceptionHandler { //定义错误显示页,error.html public static final String DEFAULT_ERROR_VIEW="error"; @ExceptionHandler(value = Exception.class) public Object defaultErrorHandler(HttpServletRequest request,Exception e) { class ErrorInfo { private Integer code; private String message; private String url; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } ErrorInfo info = new ErrorInfo(); info.setCode(100); info.setMessage(e.getMessage()); info.setUrl(request.getRequestURL().toString()); return info; }}

如何配置springboot错误页,配置全局异常
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢