Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Rest服务引发异常:处理异常的最佳方法_Java_Rest_Jakarta Ee_Jersey - Fatal编程技术网

Java Rest服务引发异常:处理异常的最佳方法

Java Rest服务引发异常:处理异常的最佳方法,java,rest,jakarta-ee,jersey,Java,Rest,Jakarta Ee,Jersey,我有一个rest服务,它会抛出一个异常,我想知道处理这个问题的最佳方法是什么 所以我有一个rest服务,它可以抛出一个用户定义的异常,我在catch块中捕捉到它并再次抛出该异常!并使用rest框架捕捉到这一点。类似地,对于非用户定义的异常。我认为这会很好,因为我有很多rest服务,所有userdefinedexception代码处理都在同一个位置 我想知道这是rest服务中处理异常的正确方法吗 我用的是运动衫 // rest service @POST public void doSometh

我有一个rest服务,它会抛出一个异常,我想知道处理这个问题的最佳方法是什么

所以我有一个rest服务,它可以抛出一个用户定义的异常,我在catch块中捕捉到它并再次抛出该异常!并使用rest框架捕捉到这一点。类似地,对于非用户定义的异常。我认为这会很好,因为我有很多rest服务,所有userdefinedexception代码处理都在同一个位置

我想知道这是rest服务中处理异常的正确方法吗

我用的是运动衫

// rest service @POST public void doSomething() { try { // ... some piece of code that can throw user defined exception as well as runtime exception } catch(UserDefinedException e) { throws new UserDefinedException(e); } catch(Exception e) { throws new ServiceException(e); } // Now I have a @Provider to catch this thrown exception @Provider public class UserDefinedExceptionHandler implements ExceptionMapper { public Response toResponse(UserDefinedException exception) { ClientResponse clientResponse = new ClientResponse(); ResponseStatus status = new ResponseStatus(); clientResponse = handleUserDefinedException(exception, status, clientResponse); return Response.ok(clientResponse).build(); } // similarly for the ServiceException //休息服务 @职位 公共无效剂量测定法(){ 试一试{ //…一些可以引发用户定义异常和运行时异常的代码 }捕获(UserDefinedException e){ 抛出新的UserDefinedException(e); }捕获(例外e){ 抛出新的ServiceException(e); } //现在我有一个@Provider来捕获这个抛出的异常 @提供者 公共类UserDefinedExceptionHandler实现 例外情况{ 对响应的公共响应(UserDefinedException异常){ ClientResponse ClientResponse=新ClientResponse(); ResponseStatus状态=新ResponseStatus(); clientResponse=handleUserDefinedException(异常、状态、clientResponse); 返回Response.ok(clientResponse.build(); } //ServiceException也是如此
在REST服务中处理异常与在任何其他代码段中处理异常没有太大区别


唯一的“公约”如果客户端发送不正确的数据触发异常,则抛出HTTP 400;如果服务意外失败,则抛出HTTP 500。

仅在服务器上引发错误500,不提供有关错误的详细信息。优雅地处理错误的一种方法是,如果状态为如果出现错误,请显示正确的消息

类似于json格式的内容:

{
    "status": "error",
    "data": {
        "message": "detailed error message"
    }
}

是的,我知道,但我想知道我抛出异常和捕获异常的方式是否正确?好的。那么你的问题是关于使用Jersey注入提供程序来处理异常?检查是的,我知道,但我想知道我抛出异常和捕获异常的方式是否正确?我基本上是throwing异常两次,一次在服务内部,一次在catch块内部,由rest frameworkcorrect处理,这是一个非常相对的概念:)取决于您的项目、团队、预算等可能的重复