package com.common.excption; import com.common.util.Result; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; @RestControllerAdvice public class GlobalExceptionHandler { //没有这个包要加一下 final static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.OK) public Result exception(Exception e) { log.error("全局异常信息 ex={}", e.getMessage(), e); return Result.error(); } @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class}) @ResponseStatus(HttpStatus.OK) public Result bodyValidExceptionHandler(MethodArgumentNotValidException exception) { List fieldErrors = exception.getBindingResult().getFieldErrors(); log.warn(fieldErrors.get(0).getDefaultMessage()); return Result.error(0, fieldErrors.get(0).getDefaultMessage()); } }