Return exception from JAX-RS Rest Service as JSON

前端 未结 4 1764
一生所求
一生所求 2021-01-16 03:19

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

4条回答
  •  Happy的楠姐
    2021-01-16 03:57

    It will respond as JSON.

    @Provider
    @Singleton
    public class ExceptionMapperProvider implements ExceptionMapper
    {
    
        @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;
        }
    }
    

提交回复
热议问题