记录自己第二个项目(SpringBoot2.7.2)遇到的问题

错误处理

1.处理所有的异常信息,包括捕获不到的400、401等等(进入controller之前)

SpringBoot官方文档:

BasicErrorController可以用作自定义的基 类ErrorController。如果您想为新的内容类型添加处理程序,这特别有用(默认是text/html专门处理并为其他所有内容提供后备)。为此,请扩展BasicErrorController,添加一个@RequestMapping具有produces属性的公共方法,并创建一个新类型的 bean

@RestController
public class MyErrorController extends BasicErrorController {



    public MyErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {

        // 获取原始错误信息
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        
        HttpStatus status = getStatus(request);

        Map<String, Object> result = new HashMap<>();
        result.put("success","false");
        result.put("code", body.get("status"));
        result.put("errorMessage", body.get("error"));
        
        return new ResponseEntity<>(result,status);
    }




}

其中getErrorAttributes之前是使用的是isIncludeStackTrace但是报错
报错原因为:boolean无法转换为org.springframework.boot.web.error.ErrorAttributeOptions

2.自定义异常(进入controller之后的异常)

Springboot文档:

定义一个带有注释的类@ControllerAdvice来自定义 JSON 文档以返回特定控制器和/或异常类型

1.根据业务的要求来定义异常类,继承自RuntimeException。RuntimeException是一个非检查型异常,在编译过程中,并不会去检查,可以顺利编译通过

public class MyException extends RuntimeException{

    private String code;

    private String errorMessage;

    public MyException(String code,String errorMessage){
        this.code = code;
        this.errorMessage = errorMessage;
    }

    public MyException(ResultCodeEnum resultCodeEnum){
        this.code = resultCodeEnum.getCode();
        this.errorMessage = resultCodeEnum.getMessage();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;

    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("MyException{");
        sb.append("code='").append(code).append('\'');
        sb.append(", errorMessage='").append(errorMessage).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

1.使用@ExceptionHandler注解捕获指定或自定义的异常;
2.使用@ControllerAdvice集成@ExceptionHandler的方法到一个类中;

@ControllerAdvice
public class MyControllerAdvice extends ResponseEntityExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(MyControllerAdvice.class);

    /**
     * 自定义异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler({ MyException.class })
    public E error(MyException e) {
        
        logger.error("catch exception,", e);
        return E.error(e.getErrorMessage());
    }


    /**
     * 通用异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler({Exception.class})
    public E error(Exception e){

        return E.error();
    }

    /*--------- 指定异常处理 ---------**/


    /**
     * 空指针异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler({NullPointerException.class})
    public E error(NullPointerException e){

        return E.error(ResultCodeEnum.NULL_POINTER_ERROR);
    }

    @ResponseBody
    @ExceptionHandler({ArithmeticException.class})
    public E error(ArithmeticException e){

        return E.error("除母不能为0");
    }
}

2022年08月02日

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值