我通过了春季异常处理文档,我没有掌握如何处理ajax调用未处理的输出的想法。
在一个应用程序中,处理页面请求、未处理异常和ajax调用未处理异常的简便方法是什么?
这可能是一个问题,因为全局异常处理程序还会捕获ajax调用并返回“专用错误页”,其中包含大量内容,从而防止为ajax错误回调提供很小的错误答复。
发布于 2016-10-03 02:33:07
在rest控制器中有三种处理异常的方法:
用@ResponseStatus和正确的HTTP结果代码注释您的异常,这些代码在抛出异常时应该返回。
例如:如果引发PersonNotFoundExcepition,则将HTTP404返回给客户端(未找到)
@ResponseStatus(HttpStatus.NOT_FOUND)
public class PersonNotFoundException { … }
另一种方法是在控制器中带有@ExceptionHandler注释的方法。在@ExceptionHandler注释的值中,您定义了应该捕获哪些异常。此外,还可以在同一方法上添加@ResponseStatus注释,以定义应该将哪些HTTP结果代码返回给客户端。
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler({PersonNotFoundException.class})
public void handlePersonNotFound() {
...
}
首选方法:将ResponseEntityExceptionHandler接口实现为@ControllerAdvice。通过这种方式,您可以将异常处理逻辑应用于所有具有集中异常处理的控制器。您可以在教程这里中阅读更多内容。
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
...
@Override
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String unsupported = "Unsupported content type: " + ex.getContentType();
String supported = "Supported content types: " + MediaType.toString(ex.getSupportedMediaTypes());
ErrorMessage errorMessage = new ErrorMessage(unsupported, supported);
return new ResponseEntity(errorMessage, headers, status);
}
...
}
请注意,对于所有类型的异常,不应返回泛型500 - Internal server error
。通常,您希望有400 s的结果范围客户端错误-错误的请求。和500 s的结果代码范围到服务器端的错误。此外,最好根据发生的情况返回更具体的代码,而不是仅仅返回400或500。
发布于 2017-05-12 00:03:23
我在全局异常处理程序中使用请求头将ajax调用和序号页请求拆分为不同的解决方案。对于ajax、无效用户输入、异常类型和内部服务器错误,也有不同的错误响应。
...
public class Application extends SpringBootServletInitializer {
@Bean(name = "simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
r.setDefaultErrorView("forward:/errorController");
return r;
}
@Controller
public class ErrorController {
public static final Logger LOG = Logger.getLogger(ErrorController.class);
@RequestMapping(value = "/errorController")
public ModelAndView handleError(HttpServletRequest request,
@RequestAttribute("exception") Throwable th) {
ModelAndView mv = null;
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
if (isBusinessException(th)) {
mv = new ModelAndView("appAjaxBadRequest");
mv.setStatus(BAD_REQUEST);
} else {
LOG.error("Internal server error while processing AJAX call.", th);
mv = new ModelAndView("appAjaxInternalServerError");
mv.setStatus(INTERNAL_SERVER_ERROR);
}
mv.addObject("message", getUserFriendlyErrorMessage(th).replaceAll("\r?\n", "<br/>"));
} else {
LOG.error("Cannot process http request.", th);
mv = new ModelAndView("appErrorPage");
mv.addObject("exeption", th);
}
return mv;
}
}
https://stackoverflow.com/questions/39829252
复制相似问题