package com.tourguide.common.exception;
|
|
import com.tourguide.common.api.ApiResponse;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.http.HttpStatus;
|
import org.springframework.validation.BindException;
|
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 javax.validation.ConstraintViolationException;
|
|
@RestControllerAdvice
|
public class GlobalExceptionHandler {
|
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
|
@ExceptionHandler(BusinessException.class)
|
public ApiResponse<Void> handleBusinessException(BusinessException exception) {
|
return ApiResponse.failure(exception.getCode(), exception.getMessage());
|
}
|
|
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class, ConstraintViolationException.class})
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
public ApiResponse<Void> handleValidationException(Exception exception) {
|
String message = "请求参数不合法";
|
if (exception instanceof MethodArgumentNotValidException && ((MethodArgumentNotValidException) exception).getBindingResult().getFieldError() != null) {
|
message = ((MethodArgumentNotValidException) exception).getBindingResult().getFieldError().getDefaultMessage();
|
} else if (exception instanceof BindException && ((BindException) exception).getBindingResult().getFieldError() != null) {
|
message = ((BindException) exception).getBindingResult().getFieldError().getDefaultMessage();
|
} else if (exception instanceof ConstraintViolationException) {
|
message = exception.getMessage();
|
}
|
return ApiResponse.failure(400, message);
|
}
|
|
@ExceptionHandler(Exception.class)
|
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
public ApiResponse<Void> handleException(Exception exception) {
|
LOGGER.error("未处理异常", exception);
|
return ApiResponse.failure(500, "服务器内部错误");
|
}
|
}
|