|
@@ -0,0 +1,41 @@
|
|
|
+package com.csm.huahai.common.handler;
|
|
|
+
|
|
|
+import com.csm.huahai.common.core.controller.domain.AjaxResult;
|
|
|
+import org.slf4j.Logger;
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
+import org.springframework.http.HttpStatus;
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.validation.FieldError;
|
|
|
+import org.springframework.web.bind.MethodArgumentNotValidException;
|
|
|
+import org.springframework.web.bind.annotation.ControllerAdvice;
|
|
|
+import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
|
+import org.springframework.web.context.request.WebRequest;
|
|
|
+
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+@ControllerAdvice
|
|
|
+public class GlobalExceptionHandler {
|
|
|
+
|
|
|
+ private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
|
|
+
|
|
|
+ @ExceptionHandler(MethodArgumentNotValidException.class)
|
|
|
+ public ResponseEntity<?> paramCheckException(MethodArgumentNotValidException ex, WebRequest request) {
|
|
|
+ Map<String, String> errors = new HashMap<>();
|
|
|
+ ex.getBindingResult().getAllErrors().forEach((error) -> {
|
|
|
+ String fieldName = ((FieldError) error).getField();
|
|
|
+ String errorMessage = error.getDefaultMessage();
|
|
|
+ errors.put(fieldName, errorMessage);
|
|
|
+ });
|
|
|
+ String res = String.join(",", errors.values());
|
|
|
+ return new ResponseEntity<>(AjaxResult.error(res), HttpStatus.OK);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 处理所有其他异常
|
|
|
+ @ExceptionHandler(Exception.class)
|
|
|
+ public ResponseEntity<?> globalExceptionHandler(Exception ex, WebRequest request) {
|
|
|
+ logger.error("Unexpected exception occurred: ", ex);
|
|
|
+ return new ResponseEntity<>(AjaxResult.error(ex.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|