自定义异常

springboot自定义异常

//运行期异常方法上面不需要throws 异常
public class CustomException extends RuntimeException {

//错误代码
ResultCode resultCode;

public CustomException(ResultCode resultCode){
    this.resultCode = resultCode;
}
public ResultCode getResultCode(){
    return resultCode;
}

}
public class ExceptionCast {

public static void cast(ResultCode resultCode){
    throw new CustomException(resultCode);
}

}
@ControllerAdvice//控制器增强
public class ExceptionCatch {

private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);

//定义map,配置异常类型所对应的错误代码
private static ImmutableMap<Class<? extends Throwable>,ResultCode> EXCEPTIONS;
//定义map的builder对象,去构建ImmutableMap
protected static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder = ImmutableMap.builder();

//捕获CustomException此类异常
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseResult customException(CustomException customException){
    customException.printStackTrace();
    //记录日志
    LOGGER.error("catch exception:{}",customException.getMessage());
    ResultCode resultCode = customException.getResultCode();
    return new ResponseResult(resultCode);
}
//捕获Exception此类异常
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult exception(Exception exception){
    exception.printStackTrace();
    //记录日志
    LOGGER.error("catch exception:{}",exception.getMessage());
    if(EXCEPTIONS == null){
        EXCEPTIONS = builder.build();//EXCEPTIONS构建成功
    }
    //从EXCEPTIONS中找异常类型所对应的错误代码,如果找到了将错误代码响应给用户,如果找不到给用户响应99999异常
    ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
    if(resultCode !=null){
        return new ResponseResult(resultCode);
    }else{
        //返回99999异常
        return new ResponseResult(CommonCode.SERVER_ERROR);
    }


}

static {
    //定义异常类型所对应的错误代码
    builder.put(HttpMessageNotReadableException.class,CommonCode.INVALID_PARAM);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值