Spring Boot中的统一异常处理
- Result为封装传递给前端的包装类
- 全局异常处理
- /**
- * Created with IntelliJ IDEA.
- *
- * @Author: KeYu
- * @Package: com.feiyu.common.exception
- * @Date: 2023/05/17/9:05
- * @说明:统一异常处理
- */
- @ControllerAdvice
- public class GlobalExceptionHandler {
- /**
- * 全局异常处理,执行方法
- * @param e
- * @return
- */
- @ExceptionHandler(Exception.class) //这里是要捕获的异常类Exception
- @ResponseBody //这里返回数据
- public Result error(Exception e){
- e.printStackTrace(); //输出错误
- return Result.fail().massage("执行了全局异常处理。。。。。");
- }
- }
复制代码- /**
- * Created with IntelliJ IDEA.
- *
- * @Author: KeYu
- * @Package: com.feiyu.common.exception
- * @Date: 2023/05/17/9:05
- * @说明:统一异常处理
- */
- @ControllerAdvice
- public class GlobalExceptionHandler {
- /**
- * 特定异常处理
- * @param e
- * @return
- */
- @ExceptionHandler(ArithmeticException.class) //这里是要捕获的异常类ArithmeticException
- @ResponseBody
- public Result error(ArithmeticException e){
- e.printStackTrace();
- return Result.fail().massage("执行了特定异常处理。。。。。");
- }
- }
复制代码- /**
- * Created with IntelliJ IDEA.
- *
- * @Author: KeYu
- * @Package: com.feiyu.common.exception
- * @Date: 2023/05/17/9:23
- * @说明:自定义异常类
- */
- @Data
- public class FeiYuException extends RuntimeException{
- private Integer code;
- private String msg;
- public FeiYuException(Integer code,String msg){
- super(msg);
- this.code = code;
- this.msg = msg;
- }
- /**
- * 接收枚举类对象
- */
- public FeiYuException(ResultCodeEnum resultCodeEnum){
- super(resultCodeEnum.getMessage());
- this.code = resultCodeEnum.getCode();
- this.msg=resultCodeEnum.getMessage();
- }
- }
复制代码- @ApiOperation("查询所有角色")
- @GetMapping("/findAll")
- public Result findAll(){
- try {
- int a = 10/0;
- }catch (Exception e){
- //抛出自定义异常
- throw new FeiYuException(20001,"执行了自定义异常");
- }
- List<SysRole> list = sysRoleService.list();
- return Result.success(list);
- }
复制代码- package com.feiyu.common.exception;
- import com.feiyu.result.Result;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
- /**
- * Created with IntelliJ IDEA.
- *
- * @Author: KeYu
- * @Package: com.feiyu.common.exception
- * @Date: 2023/05/17/9:05
- * @说明:统一异常处理
- */
- @ControllerAdvice
- public class GlobalExceptionHandler {
- //自定义异常
- @ExceptionHandler(FeiYuException.class) //这里是要捕获的异常类FeiYuException(自定义异常类)
- @ResponseBody
- public Result error(FeiYuException e){
- e.printStackTrace();
- return Result.fail().code(e.getCode()).massage(e.getMessage());
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |