我正在设置一个处理异常的方法,并且如果它是ajax请求,我想返回对象。如果不是,我想在我的Spring Boot Web应用程序中返回视图。它可以成功返回视图,但是当返回对象时,响应就是抛出异常的堆栈。
@ControllerAdvice
public class GenericExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
protected Object handleConflict(RuntimeException ex, WebRequest request) {
if (isAjaxRequest(request)) {
AjaxResult aResult = new AjaxResult();
aResult.setStatus(Status.ERROR);
aResult.setMessage(NoticeMessages.ERROR);
return aResult;
}
return "503";
}
private boolean isAjaxRequest(WebRequest request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
}