当抛出未经检查的异常时,ExceptionHandlers是否有办法输出参数?

时间:2013-12-12 01:39:14

标签: java spring debugging exception-handling unchecked

@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个端点。

1 个答案:

答案 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";
}

你应该让属性键保持不变。