Files
aida-buyer/src/main/java/com/aida/buyer/common/exception/GlobalExceptionHandler.java
litianxiang ac7de27099 first
2026-05-15 15:09:21 +08:00

54 lines
2.0 KiB
Java

package com.aida.buyer.common.exception;
import com.aida.buyer.common.result.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<Response<Void>> handleUnauthorizedException(UnauthorizedException e) {
log.error("Unauthorized: {}", e.getMessage());
return new ResponseEntity<>(
Response.fail(401, e.getMessage()),
HttpStatus.UNAUTHORIZED
);
}
@ExceptionHandler(BusinessException.class)
public Response<Void> handleBusinessException(BusinessException e) {
return Response.fail(e.getCode(), e.getMsg());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Response<Void> handleValidationException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.findFirst()
.orElse("validation error");
return Response.fail(-2, message);
}
@ExceptionHandler(BindException.class)
public Response<Void> handleBindException(BindException e) {
String message = e.getBindingResult().getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.findFirst()
.orElse("bind error");
return Response.fail(-2, message);
}
@ExceptionHandler(Exception.class)
public Response<Void> handleException(Exception e) {
log.error("system error: ", e);
return Response.error("系统繁忙");
}
}