java - 指定 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
解决方案
推荐阅读
- python - Flaskwebgui 在网络上不可见
- python - 如何在 Python 类中创建接受参数的 Setter 和 Getter
- python - 使用 Linux 命令(或 python)计算日志文件中打印时间的平均值?
- json - 将 JSON 数组中的数据收集到 ClickHouse 表中
- javascript - AWS Lambda:如何在 event.body 中获取属性,它保持返回未定义
- jquery - 如何在 asp.net 核心中使用 ajax 将用户的 questionId 和答案发送到控制器
- javascript - 有什么方法可以捕获nodejs中异步回调抛出的异常(外部)?
- ruby-on-rails - 授予 cancan 自动创建的能力是否意味着可以访问新操作?
- java - 为什么 JDK 开发人员在某处不遵循变量命名约定?
- google-apps-script - 新编码器故障排除 TypeError