SpringBoot--全局异常

我们在做后台开发的时候,出现错误是很正常的,SpringBoot异常报错有一默认的映射:/error,当出现错误的时候,SpringBoot会转到该请求中,并且这个请求还有一个全局的错误页面来展示这个错误。

新建一个SpringBoot项目,代码如下:

@Controller
public class TestController {
    @GetMapping("/test")
    public String test() throws  Exception{
       int a=1/0;
       return "test";
    }
}

然后访问http://localhost:8080/test,就会出现以下报错的页面,这个页面就是默认的error页面

异常统一处理

虽然SpringBoot存在默认的error错误页,但是显示的信息不够友好,需要我们对其进行修改,修改过程如下:

  • 创建全局异常类:通过使用**@RestControllerAdvice+@ExceptionHandler**进行全局异常处理,就不需要在所有的Controller中定义异常。代码如下:

    @RestControllerAdvice
    public class GlobalExceptionHandler {
        public static final String ERROR_VIEW = "error";
        @ExceptionHandler(value = Exception.class)
        public ModelAndView exceptionError(HttpServletRequest req, Exception e) throws Exception{
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", req.getRequestURL());
            mav.setViewName(ERROR_VIEW);
            return mav;
        }
    }

     

  • @RestControllerAdvice用于获取Controller层的异常,并返回JSON格式。

  • @ExceptionHandler是一种统一处理异常的注解,用于减少代码重复率,降低复杂度。

  • 实现自定义的error.html页面展示,放在src\main\resources\templates目录下代码如下:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org">
    <head lang="en">
        <meta charset="UTF-8" />
        <title>异常统一处理</title>
    </head>
    <body>
    <h1>异常统一处理</h1>
    <div >
        错误请求地址:<label th:text="${url}"></label><br/>
        错误信息:<label th:text="${exception.message}"></label><br/>
    </div>
    </body>
    </html>

  • 启动项目,访问http://localhost:8080/test,显示结果如下:

  •  

  • 自定义异常处理:

创建一个统一的异常处理实体:

@Data
public class Result<T> implements Serializable {
    public static final Integer SUCCESS = 200;
    public static final Integer FAILURE_ERROR = 404;
    private static final long serialVersionUID = 1L;
    /**
     * 代码
     */
    private int code;
    /**
     * 信息
     */
    private String msg;
    /**
     * 时间
     */
    private long time;
    /**
     * 数据实体
     */
    private T data;
}

 创建GlobalException自定义的全局异常处理类

public class GlobalException extends Exception{
    public GlobalException(String msg){
        super(msg);
    }
}

在Controller层创建一个测试方法

    @GetMapping("/testexception")
    public String testexception() throws GlobalException {
        throw new GlobalException("发生test错误2");
    }

修改GlobalException异常创建对应的处理

@RestControllerAdvice
public class GlobalExceptionHandler {
    public static final String ERROR_VIEW = "error";
    @ExceptionHandler(value = GlobalException.class)
    public  Result<String> exceptionError(HttpServletRequest req, GlobalException e) throws Exception{
//        ModelAndView mav = new ModelAndView();
//        mav.addObject("exception", e);
//        mav.addObject("url", req.getRequestURL());
//        mav.setViewName(ERROR_VIEW);
        Result<String> result = new Result<>();
        result.setTime( System.currentTimeMillis());
        result.setMsg(e.getMessage());
        result.setCode(404);
        result.setData(req.getRequestURL().toString());
        return result;
    }
}

启动应用,访问:http://localhost:8080/testexception,可以得到如下返回内容:

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot中,可以通过定义全局异常来处理应用程序中的异常情况。以下是一种常见的处理方法: 1. 创建一个全局异常处理类,可以命名为 `GlobalExceptionHandler`。 ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { // 处理异常,并返回合适的响应 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error"); } // 可以添加其他异常处理方法,比如处理特定类型的异常 // @ExceptionHandler(YourCustomException.class) // public ResponseEntity<String> handleYourCustomException(YourCustomException ex) { // // 处理自定义异常,并返回合适的响应 // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage()); // } } ``` 2. 在 `GlobalExceptionHandler` 类上使用 `@ControllerAdvice` 注解,表示它是一个全局异常处理类。 3. 在 `GlobalExceptionHandler` 类中,使用 `@ExceptionHandler` 注解来指定要处理的异常类型,比如 `Exception.class` 表示处理所有异常。 4. 在异常处理方法中,可以根据实际情况进行异常处理,并返回合适的响应。在上述示例中,我们处理了 `Exception` 类型的异常,并返回了一个表示内部服务器错误的响应。 5. 可以根据需要添加其他异常处理方法,比如处理特定类型的自定义异常。在处理自定义异常时,可以根据具体的业务逻辑进行异常处理,并返回相应的响应。 通过以上步骤,我们可以实现全局异常处理,统一处理应用程序中的异常情况。这样可以使代码更加清晰,减少重复代码,并提供更好的用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值