How to expose the internal error message id in play framework 1.2.7 via json?

1.1k views Asked by At

The play framework 1.2.7 application serves a JavaScript frontend. Almost any messages between the two layers are exchanged as JSON strings. Now I need to change the 500 errors (and possibly others) from html to JSON.

I changed the app/views/error.html to

#{if play.mode.name() == 'DEV'}
  {
   "msg": "500 exception",
   "verbose": "missing",
   "type":   "${exception?.class.name}",
   "message": "${exception?.message?.replace("\"", "\\\"")}"
  }
#{/if}
#{else}
  {"msg": "500 exception"}
#{/else}

But this is missing the internal exception id, that is useful when checking the logs:

09:49:54,419 ERROR ~ 

@6gfb83i26
Internal Server Error (500) for request GET /test/500

Execution exception (In /app/controllers/Application.java around line 332)
NullPointerException occured : null

What do I need to change that the @6gfb83i26 appears in the message to the frontend for debugging purposes? Also, is there a way to re-write #{500 exception /} to write JSON instead of HTML?

1

There are 1 answers

0
ristes On BEST ANSWER

The simplest way to do this is to use the @Catch interceptor.

Here is a example controller that contains this interceptor:

public class InternalErrorController extends Controller {

    @Catch
    public static void handleExceptions(Throwable e) {
        if (e != null) {
            String result = "{ status: 500, msg: '" + e.getMessage() + "', errId: 1 }";
            response.status = 500;
            renderJSON(result);
        }
    }
}

Afterwards, for every controller for which you want to return JSON status about the error, you should add the following:

@With(InternalErrorController.class)
public class Application extends Controller {

    public static void index() {
        throw new RuntimeException("Test exception");
    }

}

This should solve your problem.