gpt4 book ai didi

spring-mvc - 用于 Restful 和正常的 Spring MVC ExceptionHandler

转载 作者:行者123 更新时间:2023-12-01 10:38:17 29 4
gpt4 key购买 nike

我想处理正常和 rest/ajax 请求的异常。这是我的代码,

@ControllerAdvice
public class MyExceptionHandler {

@ExceptionHandler(Exception.class)
public ModelAndView handleCustomException(Exception ex) {

ModelAndView model = new ModelAndView("error");
model.addObject("errMsg", ex.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
sw.toString();
model.addObject("errTrace", sw);
return model;

}

@ExceptionHandler(Exception.class)
@ResponseBody
public String handleAjaxException(Exception ex) {
JSONObject model = new JSONObject();
model.put("status", "error");
model.put("errMsg", ex.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
sw.toString();
model.put("errTrace", sw);

return model.toString();
}
}

这会给我一个错误,因为我不能使用 @ExceptionHandler(Exception.class) 两次。那么解决方案是什么?

最佳答案

看@ControllerAdvice的配置: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

因此您可以创建两个类(错误处理程序)并指定 annotations/basePackages/assignibaleTypes

例如,对于 REST(ajax),为您的 Controller 使用 @RestController 注释,您可以像这样处理错误:

@ControllerAdvice(annotations = RestController.class)
public class MyExceptionHandler {

@ExceptionHandler(Exception.class)
@ResponseBody
public String handleAjaxException(Exception ex) {
...
}
}

对于其他情况,它可以是带有注释的错误处理程序

@ControllerAdvice(annotations = Controller.class)

关于spring-mvc - 用于 Restful 和正常的 Spring MVC ExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32070793/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com