问题
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.
回答1:
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.
回答2:
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"));
}
来源:https://stackoverflow.com/questions/57690339/how-to-customly-handle-recourse-urls-not-found-in-quarkus