【问题标题】:Spring 4 mvc global exception HandlingSpring 4 mvc 全局异常处理
【发布时间】:2016-11-18 03:37:35
【问题描述】:

如果我问一个基本问题,我对 spring mvc 很陌生,我需要在 spring 4 MVC,Jersey 项目中维护全局异常处理并将 JSON 响应返回到 IOS 移动应用程序。现在通过使用@ControllerAdvice 和@ExceptionHandler,我创建了一个如下所示的类

@ControllerAdvice
public class GlobalExceptionHandlerController {

    @ExceptionHandler(Exception.class)
    public @ResponseBody handleException(HttpServletRequest reqException ex) {
            ErrorInfo response=new ErrorInfo();
                   if(ex.getMessage.contains("java.io")){
                     response.setMessage("FileNotFound exception occur");
                        return response;
                     }else if ...
    }

请告知上述方法是否正确,或者是否有任何替代方法来处理控制器、服务和 DAO 层中发生的所有异常。

【问题讨论】:

  • 这与泽西岛究竟有什么关系?我在您的帖子中看到了对泽西岛的引用,但我没有看到任何其他支持细节。

标签: spring spring-mvc jersey-2.0


【解决方案1】:

你用的是对的,所有的异常都被处理掉了并定义您自己的业务例外。 这是一些示例代码。

@ExceptionHandler(RuntimeException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorResponse handleUnexpectedServerError(RuntimeException ex) {
    ex.printStackTrace();
    return new ErrorResponse("012", ex.getMessage());
}

处理业务异常,BusinessErrorException为自定义异常。

@ExceptionHandler(BusinessErrorException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse handleBusinessErrorException(BusinessErrorExceptionex) {

    return new ErrorResponse(ex.getCode(), ex.getMessage());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-12
    • 2021-08-19
    • 2013-04-02
    • 2018-07-19
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多