forked from fdzcxy212206413/jty
parent
ba7d5d8709
commit
de12494bbd
@ -1,15 +1,22 @@
|
|||||||
package jty.expressdistributionsystem.interceptors;
|
package jty.expressdistributionsystem.interceptors;
|
||||||
|
|
||||||
import jty.expressdistributionsystem.entity.Result;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@RestControllerAdvice
|
@RestControllerAdvice
|
||||||
public class GlobalExceptionHandler {
|
public class GlobalExceptionHandler {
|
||||||
@ExceptionHandler(Exception.class)
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||||
public Result handleException(Exception e){
|
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
|
||||||
e.printStackTrace();
|
Map<String, String> errors = new HashMap<>();
|
||||||
return new Result(500, StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败", "");
|
ex.getBindingResult().getFieldErrors().forEach(error ->
|
||||||
|
errors.put(error.getField(), error.getDefaultMessage())
|
||||||
|
);
|
||||||
|
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in new issue