mbassijaphet
mbassijaphet

Reputation: 31

How to customly handle Recourse/URLs Not Found in Quarkus?

I'm very new to Quarkus and I will like to know how I can override default 404 page which provides the error logs or how I can neatly redirect all not recognized URLs to a custom HTML in the META-INF/recourses directory.

Upvotes: 3

Views: 5955

Answers (2)

Serkan
Serkan

Reputation: 1235

What you also can do is extend your own exception from WebApplicationException, instead of writing a mapper.

See below:

public class NotFoundException extends WebApplicationException {
    public NotFoundException(String msg) {
        super(msg, Response.Status.NOT_FOUND);
    }
}

And obviously throw this exception in your REST controller:

@GET
@Path("/{id}")
public MyEntity find(@PathParam("id") Long id) {
   return (MyEntity) Optional.ofNullable(MyEntity.findById(id)).orElseThrow(() -> new NotFoundException("MyEntity with given id=" + id + " not found"));
}


Upvotes: 0

Daniel Ribeiro
Daniel Ribeiro

Reputation: 182

Using quarkus 0.20+ you can create an ExceptionMapper like this:

import java.util.Scanner;

import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * NotFoundExepptionMapper
 */
@Provider
public class NotFoundExeptionMapper implements ExceptionMapper<NotFoundException> {
    @Override
    public Response toResponse(NotFoundException exception) {
        String text = new Scanner(this.getClass().getResourceAsStream("/META-INF/resources/notfound.html"), "UTF-8").useDelimiter("\\A").next();
        return Response.status(404).entity(text).build();
    }
}

Save the page on /META-INF/resources/notfound.html and it's done.

Upvotes: 7

Related Questions