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

你。 提交于 2021-01-28 17:49:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!