GlobalExceptionHandler.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package cn.yunzhixue.ability.center;
  2. import cn.yunzhixue.ability.center.kernel.BaseResponse;
  3. import cn.yunzhixue.ability.center.kernel.BusinessException;
  4. import cn.yunzhixue.ability.center.kernel.ErrorCode;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.http.HttpStatusCode;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.validation.BindException;
  10. import org.springframework.http.converter.HttpMessageNotReadableException;
  11. import org.springframework.web.bind.MethodArgumentNotValidException;
  12. import org.springframework.web.bind.MissingServletRequestParameterException;
  13. import org.springframework.web.bind.annotation.ExceptionHandler;
  14. import org.springframework.web.bind.annotation.RestControllerAdvice;
  15. import org.springframework.web.servlet.NoHandlerFoundException;
  16. import org.springframework.web.servlet.resource.NoResourceFoundException;
  17. @RestControllerAdvice
  18. public class GlobalExceptionHandler {
  19. private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  20. @ExceptionHandler(BusinessException.class)
  21. public ResponseEntity<BaseResponse<Void>> handleBusinessException(BusinessException exception) {
  22. return ResponseEntity
  23. .status(HttpStatusCode.valueOf(exception.getErrorCode().getHttpStatusCode()))
  24. .body(BaseResponse.failure(exception.getErrorCode()));
  25. }
  26. @ExceptionHandler({
  27. MissingServletRequestParameterException.class,
  28. MethodArgumentNotValidException.class,
  29. BindException.class,
  30. HttpMessageNotReadableException.class})
  31. public ResponseEntity<BaseResponse<Void>> handleValidationException(Exception exception) {
  32. return ResponseEntity
  33. .status(HttpStatusCode.valueOf(ErrorCode.VALIDATION_ERROR.getHttpStatusCode()))
  34. .body(BaseResponse.failure(ErrorCode.VALIDATION_ERROR));
  35. }
  36. @ExceptionHandler({NoHandlerFoundException.class, NoResourceFoundException.class})
  37. public ResponseEntity<BaseResponse<Void>> handleNotFoundException(Exception exception) {
  38. return ResponseEntity.notFound().build();
  39. }
  40. @ExceptionHandler(Exception.class)
  41. public ResponseEntity<BaseResponse<Void>> handleException(Exception exception) {
  42. log.error("Unhandled exception caught by global handler", exception);
  43. return ResponseEntity
  44. .status(HttpStatusCode.valueOf(ErrorCode.INTERNAL_ERROR.getHttpStatusCode()))
  45. .body(BaseResponse.failure(ErrorCode.INTERNAL_ERROR));
  46. }
  47. }