【问题标题】:Throw exception inside @ExceptionHandler在@ExceptionHandler 中抛出异常
【发布时间】:2016-11-04 11:10:54
【问题描述】:

当我在@ExceptionHandler 内抛出异常throw new ForbiddenAjaxException()

  @ExceptionHandler({ ForbiddenException.class })
  public String forbiddenException(HttpServletRequest request, HttpServletResponse response)  {

        if( "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) ){
            throw new ForbiddenAjaxException();
        }

        return "redirect:/projects/error";
  }

它没有回复@ResponseStatus( HttpStatus.FORBIDDEN )

@ResponseStatus( HttpStatus.FORBIDDEN )
public class ForbiddenAjaxException extends RuntimeException  {}

日志错误:

11:00:06.277 [http-nio-8080-exec-8] ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: public java.lang.String controller.projects.ExceptionHandling.forbiddenException(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
exceptions.ForbiddenAjaxException
    at controller.projects.ExceptionHandling.forbiddenException(ExceptionHandling.java:33) ~[classes/:?]

P.S : 当ForbiddenException(正常请求不是 ajax 请求)被抛出时,它会被异常处理程序捕获。

【问题讨论】:

  • 如果你直接从控制器抛出ForbiddenAjaxException会发生什么?
  • @Ralph 如果我直接从控制器抛出 ForbiddenAjaxException,它会起作用
  • 可以添加异常处理程序和控制器代码的完整代码吗?
  • 删除@ExceptionHandler 会发生什么

标签: java spring spring-mvc


【解决方案1】:

你可以使用下面的

  @ExceptionHandler({ ForbiddenException.class })
  public Object forbiddenException(HttpServletRequest request, HttpServletResponse response)  {

        if( "XMLHttpRequest".equals(request.getHeader("X-Requested-With")) ){
             return new ResponseEntity(HttpStatus.FORBIDDEN);
        }

        return "redirect:/projects/error";
  }

【讨论】:

    猜你喜欢
    • 2011-02-21
    • 2020-06-02
    • 2014-05-29
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2021-12-24
    • 2021-01-15
    • 2012-01-24
    相关资源
    最近更新 更多