File tree Expand file tree Collapse file tree
java/com/baeldung/servlets Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .servlets ;
2+
3+ import javax .servlet .annotation .*;
4+ import javax .servlet .http .*;
5+ import java .io .*;
6+ import java .util .*;
7+
8+ import static javax .servlet .RequestDispatcher .*;
9+
10+ @ WebServlet (urlPatterns = "/errorHandler" )
11+ public class ErrorHandlerServlet extends HttpServlet {
12+
13+ @ Override
14+ protected void doGet (HttpServletRequest req , HttpServletResponse resp )
15+ throws IOException {
16+ resp .setContentType ("text/html; charset=utf-8" );
17+ try (PrintWriter writer = resp .getWriter ()) {
18+ writer .write ("<html><head><title>Error description</title></head><body>" );
19+ writer .write ("<h2>Error description</h2>" );
20+ writer .write ("<ul>" );
21+ Arrays .asList (ERROR_STATUS_CODE , ERROR_EXCEPTION_TYPE , ERROR_MESSAGE )
22+ .forEach (e ->
23+ writer .write ("<li>" + e + ":" + req .getAttribute (e ) + " </li>" )
24+ );
25+ writer .write ("</ul>" );
26+ writer .write ("</html></body>" );
27+ }
28+
29+ Exception exception = (Exception ) req .getAttribute (ERROR_EXCEPTION );
30+ if (IllegalArgumentException .class .isInstance (exception )) {
31+ getServletContext ().log ("Error on an application argument" , exception );
32+ }
33+ }
34+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .servlets ;
2+
3+ import javax .servlet .annotation .*;
4+ import javax .servlet .http .*;
5+
6+ @ WebServlet (urlPatterns = "/randomError" )
7+ public class RandomErrorServlet extends HttpServlet {
8+
9+ @ Override
10+ protected void doGet (HttpServletRequest req , final HttpServletResponse resp ) {
11+ throw new IllegalStateException ("Random error" );
12+ }
13+ }
Original file line number Diff line number Diff line change 1+ <web-app xmlns : xsi =" http://www.w3.org/2001/XMLSchema-instance"
2+ xmlns =" http://java.sun.com/xml/ns/javaee"
3+ xsi : schemaLocation =" http://java.sun.com/xml/ns/javaee
4+ http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
5+ version =" 3.1" >
6+
7+ <error-page >
8+ <error-code >404</error-code >
9+ <location >/error-404.html</location > <!-- /src/main/webapp/error-404.html-->
10+ </error-page >
11+
12+ <error-page >
13+ <exception-type >java.lang.Exception</exception-type >
14+ <location >/errorHandler</location >
15+ </error-page >
16+ </web-app >
Original file line number Diff line number Diff line change 1+ <!DOCTYPE html>
2+ < html lang ="en ">
3+ < head >
4+ < meta charset ="UTF-8 ">
5+ < title > Error page</ title >
6+ </ head >
7+ < body >
8+
9+ < h2 > Error: Page not found</ h2 >
10+
11+ < a href ="./ "> Go back home</ a >
12+
13+ </ body >
14+ </ html >
You can’t perform that action at this time.
0 commit comments