Custom Http Response Exception Mapper in Javalin Server

257 Views Asked by At

How can we implement a custom exception mapper in the Javalin frame work? The main issue I am having with the default one is that it includes a type field in its json responses that identifies it as a javalin exception. I don't wish to expose this information. It looks as follows:

{

    "title": "Internal server error.",

    "status": 500,

    "type": "https://javalin.io/documentation#error-responses",

    .....

}

The HttpResponseExceptionMapper doesn't seem to be an interface or anything that can be overridden. So I am at a loss, does anyone have any ideas?

2

There are 2 best solutions below

0
mexchip On

I'm solving it by enclosing the code in a try-catch block like this:

try {
    throw BadRequestResponse("A parameter is missing")
} catch (e: BadRequestResponse) {
    ctx.json("Bad request: ${e.message}.").status(400)
}
0
zugazagoitia On

Javalin provides out of the box support for Exception Mapping, you can just do:

app.exception(BadRequestResponse.class, (e, ctx) -> {
    ctx.json("Bad request: ${e.message}.").status(400)
});