统一异常处理

`/*
统一异常类处理
*/
@Slf4j
@RestControllerAdvice("com/atguigu/gulimall/product/controller")
public class GuliMallExceptionHandler {

@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R MethodValidExceptionHandler(MethodArgumentNotValidException e){
    log.error("数据校验异常",e.getMessage().getClass());
    BindingResult bindingResult = e.getBindingResult();
    HashMap<String, String> errorMap = new HashMap<>();
    bindingResult.getFieldErrors().forEach((error)->{
        errorMap.put(error.getField(),error.getDefaultMessage());
    });
    return R.error(ExceptionEnum.VALID_EXCEPTION.getCode(),ExceptionEnum.VALID_EXCEPTION.getMessage()).put("data",errorMap);
}

@ExceptionHandler(value = Throwable.class)
public R ThrowableExceptionHandler(Throwable throwable){
    return R.error(ExceptionEnum.UNKOWN_EXCEPTION.getCode(), ExceptionEnum.UNKOWN_EXCEPTION.getMessage());
}

}`

posted @ 2022-01-11 19:56  叶青云  阅读(45)  评论(0)    收藏  举报