HttpServer找不到资源时,在球衣中引发定制的404错误的地方 [英] Where to throw customized 404 error in jersey when HttpServer can't find a resource

查看:144
本文介绍了HttpServer找不到资源时,在球衣中引发定制的404错误的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自定义404响应,服务器(不是我)在找不到请求的资源时会抛出该错误,(或者自己抛出一个自定义的WebApplicationException,如果可以测试一个应用程序中是否存在请求的资源) (可能是资源列表存储在某处?). 请不要将我推荐给建议扩展WebApplicationException的解决方案,因为即使这样做,我的问题是何时将其抛出?何时找不到资源!但是如何在jersey框架中表达这种需求

I want to customize 404 response, that the server (not me) throws whenever it can't find a requested resource, (or throw a customized WebApplicationException myself, if it's possible to test if a requested resource is present in one app? probably a List of resources is stored somewhere?). please don't refer me to solutions that suggest to extend WebApplicationException, because even doing so, my problem is when to throw it?, when resource is not found! but how to express this need in jersey framework

推荐答案

Jersey

Jersey throws javax.ws.rs.NotFoundException when it cannot find an endpoint. Just use an exception mapper to transform it to a response of your choice:

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

@Provider
public class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {

    public Response toResponse(NotFoundException exception) {
        return Response.status(Response.Status.NOT_FOUND)
                .entity("No such resource")
                .build();
    }
}

这篇关于HttpServer找不到资源时,在球衣中引发定制的404错误的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆