Skip to content

Sending errors

Error codes

When a client makes an HTTP request to the server, the server usually responds with a status code.

Here are some of the more common status codes.

CodeStatusMeaning
200OKThe operation has succeeded
201CreatedAn entity has been created (e.g. rows inserted into the database)
204No ContentThe operation has succeeded, and the client doesn't need to do anything about it
400Bad RequestThe data sent by the client is not valid
401UnauthorizedIn order to access this endpoint, you need to send credentials
403ForbiddenThe credentials you send are not correct for this endpoint
404Not FoundThis resource is not found
500Internal Server ErrorSomething went wrong and the server will not explain why

Detailed information on all status codes can be found on MDN.

In particular, we are interested in the error codes, (400-599).

Javalin Exceptions

Javalin has some useful built in exceptions which make it easier to respond to the client when something goes wrong.

This will respond with a 404:

java
if (user == null) {
  throw new NotFoundResponse("User not found");
}

This will respond with a 400:

java
if (limit < 0 || offset < 0) {
  throw new BadRequestResponse("Limit and offset must be greater than 0");
}

Here are some useful built-in exceptions:

NameDescription
BadRequestResponseReturns a 400 Bad Request response with the default title Bad request.
UnauthorizedResponseReturns a 401 Unauthorized response with the default title Unauthorized.
ForbiddenResponseReturns a 403 Forbidden response with the default title Forbidden.
NotFoundResponseReturns a 404 Not Found response with the default title Not found.
InternalServerErrorResponseReturns a 500 Internal Server Error response with the default title Internal server error.

Fallback exception handling

If an exception is thrown which Javalin does not know how to handle, it will be passed to a global exception handler which we can customise:

java
app.exception(Exception.class, (e, ctx) -> {
  ctx.status(500);
  ctx.result("An unkown error occurred.");
});