美文网首页
java 自定异常处理

java 自定异常处理

作者: 8奈文摩尔8 | 来源:发表于2020-08-05 08:50 被阅读0次

    新建异常类 继承

    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);
    

    相关文章

      网友评论

          本文标题:java 自定异常处理

          本文链接:https://www.haomeiwen.com/subject/johdrktx.html