java 自定异常处理

2020-08-05  本文已影响0人  8奈文摩尔8

新建异常类 继承

public class HealthException extends RuntimeException {
    
    public HealthException(String message) {
        super(message);
    }
}

创建异常处理类

@RestControllerAdvice
public class HealExceptionAdvice {

    //定义方法做异常处理
    //使用注解对异常进行认领
    //统一标注返回类型
    @ExceptionHandler(HealthException.class)
    public Result handleHealthException(HealthException he) {
        return new Result(false, he.getMessage());
    }

    //未知异常处理
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        return new Result(false, "未知异常");
    }
}

使用时候直接抛出异常

throw new HealthException(message);
上一篇下一篇

猜你喜欢

热点阅读