简体   繁体   中英

How to catch already caught exception?

I have the follow the following filter:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
     ServletException {

  try {
     chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
  } catch (XssAttackException e) {
     request.getRequestDispatcher("/XssAttack").forward(request, response);
  }
}

and the class XssAttackException is:

public class XssAttackException extends RuntimeException {

private static final long serialVersionUID = 1L;

}

after debugging the code, I realized that somewhere in the spring framework all the exceptions are being caught. Now I need a way that my catch bock also run.

UPDATE

inside XSSRequestWrapper we have:

@Override
public String getHeader(String name) {

  String value = super.getHeader(name);
  return stripXSS(value);
}

And

private String stripXSS(String value) {

  if (value != null) {
     value = persianUtf8(value);
     if (!value.equals(Jsoup.parse(value).text())) {
        throw new XssAttackException();
     }
     value = Jsoup.parse(value).text();
     for (Pattern scriptPattern : patterns) {
        if (scriptPattern.matcher(value).matches()) {
           throw new XssAttackException();
        }
        value = scriptPattern.matcher(value).replaceAll("");
     }
  }
  return value;
}

Please don't assume this is answer for your question.Assumed too long comment. I created my CustomException class.

public class CustomException extends RuntimeException {
}

and created custom Servlet class as your XSSRequestWrapper and throw my custom exception in constructor.

public class MyServlet implements ServletRequest {

    public MyServlet() {
        throw new CustomException();
    }
// other override methods go here
}

and in my filter class

    try {
        chain.doFilter(new MyServlet(), response);
    } catch (CustomException e) {
        System.out.println("xxxxxxxxxxxxxxx I got it xxxxxxxxxxxxxxxxxxx");
    }

This code work fine. At your program , I think there has some exception has occured and you did not catch on them. So , this exception object has miss from your try block of your filter class and handled by Spring container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM