|  |  |  | 
|---|
|  |  |  | package com.dy.common.webUtil; | 
|---|
|  |  |  |  | 
|---|
|  |  |  | import lombok.extern.slf4j.Slf4j; | 
|---|
|  |  |  | import org.springframework.validation.BindingResult; | 
|---|
|  |  |  | import org.springframework.web.bind.MethodArgumentNotValidException; | 
|---|
|  |  |  | import org.springframework.web.bind.annotation.ControllerAdvice; | 
|---|
|  |  |  | import org.springframework.web.bind.annotation.ExceptionHandler; | 
|---|
|  |  |  | import org.springframework.web.bind.annotation.ResponseBody; | 
|---|
|  |  |  | 
|---|
|  |  |  | * 全局异常处理,处理在Controller中抛出的异常,在Controller之前(如Fileter)发生的错误或异常由GlErrorCtrl处理 | 
|---|
|  |  |  | * 此类是基于拦截器和实现指定接口(GlExceptionHandler和GlExceptionHandlerImpl) | 
|---|
|  |  |  | * 另一种实现方式是基于注解切面实现(GlExceptionAspect) | 
|---|
|  |  |  | * handleValidationExceptions()处理参数验证性异常,与 @Valid配合使用 | 
|---|
|  |  |  | */ | 
|---|
|  |  |  | @ControllerAdvice | 
|---|
|  |  |  | @ResponseBody | 
|---|
|  |  |  | 
|---|
|  |  |  | log.error("捕获到GlException:{}", e.getMsg(), e); | 
|---|
|  |  |  | return BaseResponseUtils.buildException(e.getMsg()); | 
|---|
|  |  |  | } | 
|---|
|  |  |  |  | 
|---|
|  |  |  | @ExceptionHandler | 
|---|
|  |  |  | public BaseResponse handleValidationExceptions(MethodArgumentNotValidException e) { | 
|---|
|  |  |  | log.error("捕获到验证性异常:{},异常栈轨迹:{}", e.getMessage(), e.getStackTrace()); | 
|---|
|  |  |  | // 检查是否有错误,避免空列表情况下的不必要操作 | 
|---|
|  |  |  | BindingResult bindingResult = e.getBindingResult(); | 
|---|
|  |  |  | if (bindingResult.hasErrors()) { | 
|---|
|  |  |  | StringBuilder sb = new StringBuilder(); | 
|---|
|  |  |  | bindingResult.getAllErrors().forEach(error -> { | 
|---|
|  |  |  | // 忽略了字段名的获取,如果需要可以按需恢复并使用 | 
|---|
|  |  |  | // String fieldName = ((FieldError) error).getField(); | 
|---|
|  |  |  | String errorMessage = error.getDefaultMessage(); | 
|---|
|  |  |  | sb.append(errorMessage).append(";"); | 
|---|
|  |  |  | }); | 
|---|
|  |  |  | // 优化返回值的泛型指定 | 
|---|
|  |  |  | return BaseResponseUtils.buildException(sb.substring(0, sb.length() - 1)); | 
|---|
|  |  |  | } else { | 
|---|
|  |  |  | // 如果没有错误,返回一个通用错误消息,避免返回空或null | 
|---|
|  |  |  | log.warn("预期的验证错误不存在,这可能是一个异常处理逻辑的错误。"); | 
|---|
|  |  |  | return BaseResponseUtils.buildException("发生了一个未知的验证错误。"); | 
|---|
|  |  |  | } | 
|---|
|  |  |  | } | 
|---|
|  |  |  | @ExceptionHandler | 
|---|
|  |  |  | public BaseResponse exceptionHandler(Throwable t) { | 
|---|
|  |  |  | log.error("捕获到异常:{}",t.getMessage(),t); | 
|---|
|  |  |  | return BaseResponseUtils.buildException("在Controller中或后产生异常:" + t.getMessage()); | 
|---|
|  |  |  | return BaseResponseUtils.buildException( t.getMessage()); | 
|---|
|  |  |  | } | 
|---|
|  |  |  | } | 
|---|