1111
1212import static io .jooby .MediaType .html ;
1313import static io .jooby .MediaType .json ;
14+ import static io .jooby .MediaType .text ;
1415
1516/**
1617 * Catch and encode application errors.
@@ -27,8 +28,24 @@ public interface ErrorHandler {
2728 ErrorHandler DEFAULT = (ctx , cause , statusCode ) -> {
2829 ctx .getRouter ().getLog ().error (errorMessage (ctx , statusCode ), cause );
2930
30- MediaType type = ctx .accept (Arrays .asList (json , html ));
31- if (type == null || type .equals (html )) {
31+ MediaType type = ctx .accept (Arrays .asList (html , json , text ));
32+ if (json .equals (type )) {
33+ String message = Optional .ofNullable (cause .getMessage ()).orElse (statusCode .reason ());
34+ ctx .setResponseType (json )
35+ .setResponseCode (statusCode )
36+ .send ("{\" message\" :\" " + XSS .json (message ) + "\" ,\" statusCode\" :" + statusCode .value ()
37+ + ",\" reason\" :\" " + statusCode .reason () + "\" }" );
38+ } else if (text .equals (type )) {
39+ StringBuilder message = new StringBuilder ();
40+ message .append (ctx .getMethod ()).append (" " ).append (ctx .pathString ()).append (" " );
41+ message .append (statusCode .value ()).append (" " ).append (statusCode .reason ());
42+ if (cause .getMessage () != null ) {
43+ message .append ("\n " ).append (XSS .json (cause .getMessage ()));
44+ }
45+ ctx .setResponseType (text )
46+ .setResponseCode (statusCode )
47+ .send (message .toString ());
48+ } else {
3249 String message = cause .getMessage ();
3350 StringBuilder html = new StringBuilder ("<!doctype html>\n " )
3451 .append ("<html>\n " )
@@ -63,12 +80,6 @@ public interface ErrorHandler {
6380 .setResponseType (MediaType .html )
6481 .setResponseCode (statusCode )
6582 .send (html .toString ());
66- } else {
67- String message = Optional .ofNullable (cause .getMessage ()).orElse (statusCode .reason ());
68- ctx .setResponseType (json )
69- .setResponseCode (statusCode )
70- .send ("{\" message\" :\" " + XSS .json (message ) + "\" ,\" statusCode\" :" + statusCode .value ()
71- + ",\" reason\" :\" " + statusCode .reason () + "\" }" );
7283 }
7384 };
7485
0 commit comments