Java 当抛出未检查的异常时,ExceptionHandler是否有方法输出参数?
我想要一种能够在Java 当抛出未检查的异常时,ExceptionHandler是否有方法输出参数?,java,spring,debugging,exception-handling,unchecked,Java,Spring,Debugging,Exception Handling,Unchecked,我想要一种能够在handleUncaughtException中输出变量url的方法。但是,由于异常来自另一个类Fetcher,我是否可以知道url参数可能导致此未检查异常 如果我错了,请纠正我,但我相信我不能将url作为字段存储在TestController中,因为我同时调用/content端点。您可以做的是在请求属性中设置url,然后在@ExceptionHandler中检索它 @Component public class Fetcher { private void sendGe
handleUncaughtException
中输出变量url
的方法。但是,由于异常来自另一个类Fetcher
,我是否可以知道url
参数可能导致此未检查异常
如果我错了,请纠正我,但我相信我不能将
url
作为字段存储在TestController
中,因为我同时调用/content
端点。您可以做的是在请求属性中设置url
,然后在@ExceptionHandler
中检索它
@Component
public class Fetcher {
private void sendGet(String url) {
someMethodThatCanThrowUncheckedException();
}
}
@Controller
public class TestController {
@Autowired
private Fetcher fetcher;
@RequestMapping(value = {"/content"}, method = RequestMethod.GET)
@ResponseBody
public String getContent(@RequestParam(value = "url", required = true) String url) {
fetcher.sendGet(url);
return "Success";
}
@ExceptionHandler({Exception.class})
@ResponseBody
public String handleUncaughtException(final Exception exception) {
return "An internal error has occured trying to fetch url: " + url;
}
}
然后取回它
@RequestMapping(value = {"/content"}, method = RequestMethod.GET)
@ResponseBody
public String getContent(@RequestParam(value = "url", required = true) String url, HttpServletRequest request) {
request.setAttribute("url", url);
fetcher.sendGet(url);
return "Success";
}
您可能应该将属性键设置为常量。谢谢!我决定使用request.getParameter(“url”)instead@Popcorn如果
url
来自请求参数,这将起作用。它在任何其他情况下都不起作用。
@ExceptionHandler({Exception.class})
@ResponseBody
public String handleUncaughtException(final Exception exception, HttpServletRequest request) {
String url = (String) request.getAttribute("url");
if (url != null)
return "An internal error has occured trying to fetch url: " + url;
else
return "something else";
}