休息服务抛出异常:最好的处理方式

编程入门 行业动态 更新时间:2024-10-26 19:35:49
本文介绍了休息服务抛出异常:最好的处理方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个休息服务,会抛出一个异常,我想知道最好的办法是什么。

I have a rest service which will throw an exception and I want to know what will be the best way to handle this.

所以我有一个休息服务可以抛出一个用户定义的异常,我在catch块中捕获它并再次抛出异常!并使用rest框架来捕获它。类似地,对于非用户定义的异常。我认为这会很好,因为我有多少休息服务,所有userdefinedexception代码处理将在同一个地方。

So I have a rest service which can throw a userdefined exception and I am catching that inside the catch block and throwing that exception again ! and using rest framework to catch that. Similarly for non-user defined exceptions. I thought this will be good as I have number of rest services and all userdefinedexception code handling will be at a same place.

我想知道这是正确的方法在休息服务中处理异常?

I would like to know is this the proper way of handling exception in rest service ?

我正在使用球衣。

// 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

推荐答案

只是在服务器上引发错误500没有提供有关错误的详细信息,优雅地处理错误的一种方法是将响应数据包装在具有状态和数据的结构中,如果状态是错误,则显示正确的消息。

Just raising error 500 at the server don't give much details on the error, one way to gracefully handle errors, is to wrap the response data in a structure with status and data, if the status is error, show the correct message.

json格式的这样的东西:

something like this in json format :

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

更多推荐

休息服务抛出异常:最好的处理方式

本文发布于:2023-11-16 11:09:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603736.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最好的   抛出   异常   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!