liujie
2026-09-11 4f6f15b818704079ff2e4e4719b798f48d68a335
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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, "服务器内部错误");
    }
}