在@ExceptionHandler中抛出异常

时间:2016-11-04 11:10:55

标签: java spring spring-mvc

当我在kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$ python __init__.py kurt@kurt-ThinkPad:~/Documents/Scratch/testdir$ python3 __init__.py Traceback (most recent call last): File "__init__.py", line 1, in <module> import testsubdir File "/home/kurt/Documents/Scratch/testdir/testsubdir/__init__.py", line 1, in <module> import testsubsubdir ImportError: No module named 'testsubsubdir'

中抛出异常throw new ForbiddenAjaxException()
@ExceptionHandler

它没有回复 @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  {}

P.S:当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/:?] (正常请求不是ajax请求)被抛出时,它会被异常处理程序捕获。

1 个答案:

答案 0 :(得分:0)

您可以使用以下

  @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";
  }