@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;
}
}
我想要一种能够在url
中输出变量handleUncaughtException
的方法。但是,由于异常来自另一个类Fetcher
,我有什么方法可以知道url
参数可能导致这个未经检查的异常?
如果我错了,请纠正我,但我相信我不能将url
作为字段存储在TestController
中,因为我正在同时调用/content
个端点。
答案 0 :(得分:1)
您可以做的是在请求属性中设置url
并在@ExceptionHandler
中检索它。
@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";
}
并检索它
@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";
}
你应该让属性键保持不变。