给HttpMessageNotReadableException和MissingServletRequestParameterException指定了全局错误处理器,现在当前端发送给后端的参数不对的时候也能正确返回401错误了

This commit is contained in:
高子兴 2024-07-03 14:49:17 +08:00
parent df34d7cb28
commit a38fd92801

View File

@ -2,9 +2,15 @@ package org.cmh.backend.Utils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
@ -12,4 +18,17 @@ public class GlobalExceptionHandler {
public ResponseEntity<Object> handleJwtInvalidException(JwtValidationException ex) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<Map<String, String>> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
HashMap<String, String> response = new HashMap<>();
response.put("error", ex.getMessage());
response.put("stackTrace", Arrays.toString(ex.getStackTrace()));
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}