关于REST接口异常如何在前端获取details信息

我在REST接口里抛出了一个IllegalStateException异常,发现cuba会在最终包装成RemoteException抛出去。然后在前端获取到了一个500的response,内容是responseText: “{“error”:“Server error”,“details”:”"}"。我在IllegalStateException中写入的details在RemoteException里被吞掉了,导致前端无法获取这个异常的原因。请问如何才能让前端拿到这个具体的异常信息?

RestAPI 对异常进行分类转译处理,参考这里:

要将异常信息返回到前端,可抛出特定类型的异常,比如抛出 RestApiException 类型的异常。
先这样试试。

我是使用cuba插件新建的service,但是在service里找不到RestApiException。

看代码,用CustomValidationException吧,没有把message给干掉。不理解RestApiException为啥不放到global包

如果是在core模块抛出异常,可以考虑使用 @weborld 提供的方法。
还有另外一个方法就是:扩展 RestExceptionLoggingFilter Bean,重写 doFilter 方法,在这里面进行异常处理。

   @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("REST API error", e);
            ((HttpServletResponse) response).setHeader("Content-Type", "application/json");
            ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            ErrorInfo errorInfo = new ErrorInfo("REST API error", e.getMessage());
            byte[] responseBytes = new ObjectMapper().writeValueAsBytes(errorInfo);
            response.getOutputStream().write(responseBytes);
        }
    }

扩展 CUBA Bean的方法可参考这里:
https://doc.cuba-platform.cn/manual-7.2-chs/bean_extension.html

1 个赞

使用CustomValidationException能把错误信息带到前端。
为了能使用RestApiException,我后来尝试把service从core移动到web,但是影响到了rest的自定义验证。本来我在rest里按照文档新增了一个自定义的验证,然后使用@CrossOrigin标注使得验证接口能够跨域,之前一直使用正常,但是一旦我把service移动到了web层,这个在rest自定义验证上的@CrossOrigin标注就像失效了一样,接口也无法跨域了,也没找到原因,只能又把service移回core使用CustomValidationException代替了。

我们也在英文论坛反馈了此问题,创建了 2 个 issue。

有关本issue的新回复:

其实主要是RestAPI的BUG,他的RestApiException应该放到global模块才对。