2

我想防止 spring 将 Runtimeexceptions 的完整堆栈跟踪发送到前端。我做了这样的事情:

@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception e, Object body, 
               HttpHeaders headers, HttpStatus status, WebRequest request) {
        logger.error("Error happened while executing controller.", e);
        return null;
    }
}

我的目标是只向前端发送错误代码,而不是其他任何东西。上述方法向前端返回状态 200 OK。应该返回什么而不是 null ?

4

1 回答 1

1

@ResponseStatus如果仅提供value,则使用, HttpServletResponse.setStatus(int)

此方法用于设置没有错误时的返回状态码(例如,对于 SC_OK 或 SC_MOVED_TEMPORARILY 状态码)。

如果使用此方法设置错误代码,则不会触发容器的错误页面机制。如果出现错误并且调用者希望调用 Web 应用程序中定义的错误页面,则必须使用 sendError(int, java.lang.String) 代替

如果也提供 a reason,则HttpServletResponse.sendError(int, String)使用 then 代替。

@ControllerAdvice
public class RestErrorHandler {
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "INTERNAL_SERVER_ERROR")
    @ExceptionHandler(Exception.class)
    public void handleConflict(Exception e) {
        // log me
    }
}
于 2015-07-22T19:41:29.100 回答