spark-java

how to handle exceptions in SparkJava


I'm trying to handle all exception (exception handler) for SparkJava

I am currently using try/catch blocks in each endpoint but that approach doesn't scale properly.

Something that can handle different kind of exception for return types, like 4xx or 5xx

Any alternatives like Spring/Play?


Solution

  • when using

            post("/account", (request, response) -> {
                Account account = new Gson().fromJson(request.body(), Account.class);
                accountService.add(account);
                response.status(204);
                return response;
            });
    

    you can add this,

            exception(RuntimeException.class, (e, request, response) -> {
                response.status(400);
                response.body(e.getMessage());
            });