Java:自定义全局异常处理程序始终返回200状态

时间:2016-04-12 20:12:04

标签: java rest exception-handling

我为我的程序创建了一个全局异常处理程序,它正在工作并捕获我的异常但是当我尝试从HttpServletResponse获取状态代码时,我总是获得200状态。有什么方法可以从异常类中获得正确的状态吗?或者,如果你有另一种工作,我会很感激。无法在线查找任何内容,我也不想为每个通过我的处理程序的异常对httpStatus进行硬编码。我希望用这一种方法捕获所有异常。这是我在GlobalExceptionHandler类中创建的方法(也是我使用了类的@ControllerAdvice注释):

@ExceptionHandler(value = Exception.class)
public @ResponseBody
ResponseEntity<Object> error(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {

    log.error("Error in call to " + request.getRequestURI() + " Response: " + response.toString(), e);

    ExceptionResource exception = new ExceptionResource();
    exception.setLocation(request.getRequestURI());
    exception.setStatus(response.getStatus());
    exception.setStackTrace(e.getStackTrace());

    return new ResponseEntity<>(exception, HttpStatus.valueOf(response.getStatus()));
}

2 个答案:

答案 0 :(得分:0)

如果您使用的是Spring MVC,那么您的异常需要具有以下内容:

<div class="container">
            <div class="left">
                <div class="row">
                    <table class="table table-striped">
                        <!-- table head -->
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Column1</th>
                                <th>Column2</th>
                                <th>Column3</th>
                                <th>Column4</th>
                            </tr>
                        </thead>
                    </table>
                    <iframe src="/tablecontent/content.txt" frameborder="0"></iframe>
            </div>
        </div>
   </div>

source

答案 1 :(得分:0)

答案:我不得不考虑另一个实现,但我确实找到了一种方法来获取使用@ResponseStatus注释创建的自定义异常的状态。您将需要使用它来获取状态:

<%= post.impressionist_count(:filter=>:ip_address) %>

其中exception是传递给处理程序的异常。