如何在JSON响应中生成ErrorMessage

如何在JSON响应中生成ErrorMessage,json,error-handling,Json,Error Handling,我已经实现了一个Restful Web服务,它通过启动@products(“application/JSON”) Am使用错误代码处理应用程序错误。因此,我用错误代码和错误消息形成一个对象。因此,当出现应用程序异常时,它将以XML格式生成。如何生成JSON格式的文件?是的,您可以。捕获异常并使用自定义异常类进行处理,并通过将响应内容类型设置为application/json来抛出异常类 try{ InitialContext ctx = new InitialContext();

我已经实现了一个Restful Web服务,它通过启动
@products(“application/JSON”)


Am使用错误代码处理应用程序错误。因此,我用错误代码和错误消息形成一个对象。因此,当出现应用程序异常时,它将以XML格式生成。如何生成JSON格式的文件?

是的,您可以。捕获异常并使用自定义异常类进行处理,并通过将响应内容类型设置为application/json来抛出异常类

try{
    InitialContext ctx = new InitialContext();
    TestIntf intf = (TestIntf)ctx.lookup("java:comp/env/ejb/TestImpl");         
    }catch(NamingException namingException) {
    CustomException lookupException = new CustomException("SYSJNDIE001", namingException.getMessage());
    throw lookupException;  
}
您的异常类将如下所示

public class CustomException extends Exception {

    private static final long serialVersionUID = -5358934896070563181L;

    public CustomException(String errorCode, String message) {
        super(errorCode, message);
    }
}
为异常创建提供程序类映射器

@Provider
public class FaultResponseMapper implements ExceptionMapper<CustomException> {

    @Context
    private HttpHeaders headers;

    @Override
    public Response toResponse(CustomException customException) {

        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                       .entity(customException)
                       .type(MediaType.APPLICATION_JSON).build();
    }
}
@Provider
公共类FaultResponseMapper实现ExceptionMapper{
@上下文
私有HttpHeader;
@凌驾
对响应的公共响应(CustomException CustomException){
返回Response.status(Response.status.INTERNAL\u SERVER\u错误)
.实体(客户例外)
.type(MediaType.APPLICATION_JSON).build();
}
}
请参见