Spring MVC 框架中的异常处理方法总结

Java Q&A Hub 使用 GPT-4o-mini 回答

问题:

如何处理 Spring MVC 框架中的异常?

回答:

在 Spring MVC 框架中,处理异常可以通过多种方式实现。以下是一些常用的方法:

1. 使用 @ControllerAdvice@ExceptionHandler

@ControllerAdvice 是一个用于全局处理控制器异常的注解。你可以定义一个类,使用 @ExceptionHandler 注解来处理特定的异常。

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handleException(Exception ex) {
        ModelAndView modelAndView = new ModelAndView("error");
        modelAndView.addObject("message", ex.getMessage());
        return modelAndView;
    }

    @ExceptionHandler(SpecificException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ModelAndView handleSpecificException(SpecificException ex) {
        ModelAndView modelAndView = new ModelAndView("specificError");
        modelAndView.addObject("message", ex.getMessage());
        return modelAndView;
    }
}

2. 使用 @ResponseStatus

你可以在自定义异常类上使用 @ResponseStatus 注解来指定 HTTP 状态码。

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

3. 使用 @RestControllerAdvice(针对 RESTful API)

如果你在构建 RESTful API,可以使用 @RestControllerAdvice,它会自动将返回值序列化为 JSON。

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@RestControllerAdvice
public class RestGlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse handleException(Exception ex) {
        return new ErrorResponse("Internal Server Error", ex.getMessage());
    }

    @ExceptionHandler(SpecificException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse handleSpecificException(SpecificException ex) {
        return new ErrorResponse("Bad Request", ex.getMessage());
    }
}

class ErrorResponse {
    private String error;
    private String message;

    public ErrorResponse(String error, String message) {
        this.error = error;
        this.message = message;
    }

    // getters and setters
}

4. 使用 Spring Boot 的 @ControllerAdvice

如果你使用的是 Spring Boot,@ControllerAdvice@RestControllerAdvice 的用法与上面相同,Spring Boot 会自动处理 JSON 序列化。

5. 自定义错误页面

你可以在 src/main/resources/templates 目录下创建自定义的错误页面(如 error.html),Spring 会在发生异常时自动渲染这些页面。

总结

在 Spring MVC 中处理异常的方式有很多,选择合适的方法可以提高应用的可维护性和用户体验。通常情况下,使用 @ControllerAdvice@ExceptionHandler 是最常见的做法。