从JAX-RS Rest Service作为JSON返回异常 [英] Return exception from JAX-RS Rest Service as JSON

查看:170
本文介绍了从JAX-RS Rest Service作为JSON返回异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否以某种方式将休息服务抛出的异常返回为JSON?我有一个JAX-RS休息服务,我想实现这一点。当我现在抛出它,它映射到一个HTML响应,这不是我想要的。从我所了解的一个ExceptionMapper也将其映射到HTML?有没有任何其他替代或库允许以JSON格式返回异常?

Is it in some way possible that an exception thrown from a rest service is returned as JSON? I have a JAX-RS Rest Service where I would like to achieve this. When I throw it now, it's mapped to an HTML response, which is not what i want. From what I have understood an ExceptionMapper will also map it to HTML? Is there any other alternative or libraries that allows the exception to be returned in JSON format?

推荐答案

它将作为JSON回复。

It will respond as JSON.

@Provider
@Singleton
public class ExceptionMapperProvider implements ExceptionMapper<Exception>
{

    @Override
    public Response toResponse(final Exception exception)
    {
            return Response.status(HttpStatusCodes.STATUS_CODE_SERVER_ERROR).entity(new BasicResponse(InternalStatus.UNHANDLED_EXCEPTION, exception.getMessage())).type(MediaType.APPLICATION_JSON).build();    
    }
}

@XmlRootElement
public class BasicResponse {

    public String internalStatus;

    public String message;

    public BasicResponse() {}

    public BasicResponse(String internalStatus, String message){
        this.internalStatus = internalStatus;
        this.message = message;
    }
}

这篇关于从JAX-RS Rest Service作为JSON返回异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆