From 19fd479d24fe5609fc4ba769a3a75a0417e983ee Mon Sep 17 00:00:00 2001 From: xuanzhi33 Date: Sat, 20 Jul 2024 11:29:32 +0800 Subject: [PATCH] refactor: exception handler --- .../exception/GlobalExceptionHandler.java | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/server/java/carproject-server/src/main/java/cn/xuanzhi33/carprojectserver/exception/GlobalExceptionHandler.java b/server/java/carproject-server/src/main/java/cn/xuanzhi33/carprojectserver/exception/GlobalExceptionHandler.java index c83ce65..3d14a22 100644 --- a/server/java/carproject-server/src/main/java/cn/xuanzhi33/carprojectserver/exception/GlobalExceptionHandler.java +++ b/server/java/carproject-server/src/main/java/cn/xuanzhi33/carprojectserver/exception/GlobalExceptionHandler.java @@ -6,30 +6,35 @@ 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.springframework.web.servlet.resource.NoResourceFoundException; @RestControllerAdvice public class GlobalExceptionHandler { + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Exception.class) - public ResponseEntity> handleException(Exception e) { - return new ResponseEntity<>(Result.serverError(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); + public Result handleException(Exception e) { + return Result.serverError(e.getMessage()); } @ExceptionHandler(NoResourceFoundException.class) - public ResponseEntity> handleNoResourceFoundException(NoResourceFoundException e) { - return new ResponseEntity<>(Result.error(404, "Not Found"), HttpStatus.NOT_FOUND); + @ResponseStatus(HttpStatus.NOT_FOUND) + public Result handleNoResourceFoundException(NoResourceFoundException e) { + return Result.error(404, "Not Found"); } @ExceptionHandler({MethodArgumentNotValidException.class, IllegalArgumentException.class}) - public ResponseEntity> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + @ResponseStatus(HttpStatus.BAD_REQUEST) + public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { Result res = Result.clientError(e.getMessage()); FieldError fieldError = e.getFieldError(); if (fieldError != null) { res = Result.clientError(fieldError.getDefaultMessage()); } - return new ResponseEntity<>(res, HttpStatus.BAD_REQUEST); + return res; } @ExceptionHandler(UnauthorizedException.class) - public ResponseEntity> handleUnauthorizedException(UnauthorizedException e) { - return new ResponseEntity<>(Result.error(401, e.getMessage()), HttpStatus.UNAUTHORIZED); + @ResponseStatus(HttpStatus.UNAUTHORIZED) + public Result handleUnauthorizedException(UnauthorizedException e) { + return Result.error(401, e.getMessage()); } }