| package com.xcong.excoin.configurations; | 
|   | 
| import com.xcong.excoin.common.exception.GlobalException; | 
| import com.xcong.excoin.common.response.Result; | 
| import lombok.extern.slf4j.Slf4j; | 
| import org.springframework.dao.DuplicateKeyException; | 
| import org.springframework.security.authentication.BadCredentialsException; | 
| import org.springframework.validation.FieldError; | 
| import org.springframework.web.bind.MethodArgumentNotValidException; | 
| import org.springframework.web.bind.annotation.ExceptionHandler; | 
| import org.springframework.web.bind.annotation.RestControllerAdvice; | 
|   | 
| import javax.validation.ValidationException; | 
|   | 
| /** | 
|  * @author wzy | 
|  * @date 2020-05-08 15:40 | 
|  **/ | 
| @RestControllerAdvice | 
| @Slf4j | 
| public class GlobalExceptionHandler { | 
|   | 
|     /** | 
|      * 方法参数校验 | 
|      * | 
|      * @param e | 
|      * @return | 
|      */ | 
|     @ExceptionHandler(value = {MethodArgumentNotValidException.class}) | 
|     public Result handleException(MethodArgumentNotValidException e) { | 
|         log.error(e.getMessage()); | 
|         FieldError fieldError = e.getBindingResult().getFieldError(); | 
|         if (fieldError != null) { | 
|             return Result.fail(fieldError.getDefaultMessage()); | 
|         } else { | 
|             return Result.fail("参数校验失败"); | 
|         } | 
|     } | 
|   | 
|   | 
|     @ExceptionHandler(value = {ValidationException.class}) | 
|     public Result handleException(ValidationException e) { | 
|         log.error(e.getMessage(), e); | 
|         return null; | 
|     } | 
|   | 
|     @ExceptionHandler(value = {DuplicateKeyException.class}) | 
|     public Result handleException(DuplicateKeyException e) { | 
|         log.error(e.getMessage(), e); | 
|         return null; | 
|     } | 
|   | 
|   | 
|     /** | 
|      * spring security 账户密码验证异常 | 
|      * | 
|      * @param e | 
|      * @return | 
|      */ | 
|     @ExceptionHandler(value = { BadCredentialsException.class }) | 
|     public Result handleException(BadCredentialsException e) { | 
|         log.error(e.getMessage(), e); | 
|         return Result.fail("用户名或密码错误"); | 
|     } | 
|   | 
|     @ExceptionHandler(value = {GlobalException.class}) | 
|     public Result handleException(GlobalException e) { | 
|         return Result.fail(e.getMessage()); | 
|     } | 
|   | 
|     @ExceptionHandler(value = {Exception.class}) | 
|     public Result handleException(Exception e) { | 
|         log.error(e.getMessage(), e); | 
|         return Result.fail("系统异常"); | 
|     } | 
|   | 
| } |