统一异常处理
新建exception包
包下新建GlobalExceptionHandler类
package com.atguigu.yygh.common.exception; import com.atguigu.yygh.common.result.Result; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class GlobalExceptionHandler { //全局异常处理 @ExceptionHandler(Exception.class) public Result error(Exception e){ e.printStackTrace(); return Result.fail("系统出现异常啦"); } //自定义异常处理 @ExceptionHandler(MyException.class) public Result error(MyException e){ e.printStackTrace(); return Result.fail(e.getMessage()); } }
包下新建MyException自定义异常类
package com.atguigu.yygh.common.exception; import com.atguigu.yygh.common.result.ResultCodeEnum; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * 自定义全局异常类 * * @author */ @Data @ApiModel(value = "自定义全局异常类") public class MyException extends RuntimeException { @ApiModelProperty(value = "异常状态码") private Integer code; /** * 通过状态码和错误消息创建异常对象 * @param message * @param code */ public MyException(String message, Integer code) { super(message); this.code = code; } /** * 接收枚举类型对象 * @param resultCodeEnum */ public MyException(ResultCodeEnum resultCodeEnum) { super(resultCodeEnum.getMessage()); this.code = resultCodeEnum.getCode(); } @Override public String toString() { return "MyException{" + "code=" + code + ", message=" + this.getMessage() + '}'; } }
测试代码
try { int i = 1/0; } catch (Exception e) { throw new MyException("这里计算出错了,",201); }
返回数据