首页 > 解决方案 > 指定 URI 没有路径映射时无法捕获 404 异常

问题描述

说这是我使用球衣“http://localhost:8080/messengerApp/webapi/messages”在我的 REST API 中收集消息的 URI 它以 json 形式返回所有消息

[{"message": "helo navaratnam","id": 3,"author": "xyz"},
 {"message": "hi ilango","id": 4,"author": "xyza"}
]

如果我输入这样的 uri “http://localhost:8080/messengerApp/webapi/mess” 它会产生如下的 html 响应

HTTP 状态 500 – 内部服务器错误体 {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:没有任何;}

HTTP 状态 500 – 内部服务器错误

类型状态报告

说明服务器遇到了阻止它完成请求的意外情况。

Apache Tomcat/9.0.34

我只是想通知开发人员他使用类似于下面的 json 响应发送了错误的 URI

{
    "errorCode": "404",
    "documentation": "something wrong please check your request",
    "errorMessage": "requested resource not available"
}

这是我的通用异常映射器

package com.jatha.messengerapp.exception;

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

import com.jatha.messengerapp.model.ErrorMessage;

@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable ex) {
//just to check the exception is reaching this mapper
        System.out.println("GenericExceptionMapper");

        ErrorMessage er = new ErrorMessage(ex.getMessage(),"404","something wrong please check your request");
        return Response.status(Status.NOT_FOUND)
                .entity(er)
                .build();
    }
    

}

几乎大多数异常都在这里捕获并生成 JSON。当 URI 如上所述错误时,异常到达此映射器,但生成的是 html 页面而不是 json。

仅在通用异常处理程序或一些单独的处理程序/映射器中处理此问题以捕获此问题的解决方案也非常感谢。我不想返回任何 html 页面。只想将 JSON 返回给开发人员。 我正在使用 Apache Tomcat/9.0.34 ,球衣 1.19.4

标签: javarestjerseyjax-rshttp-status-code-404

解决方案


推荐阅读