dubbox consumer获取provider的exception message

借鉴:

http://howtodoinjava.com/2013/06/03/exception-handling-in-jax-rs-resteasy-with-exceptionmapper/

http://liugang594.iteye.com/blog/1501758

http://dangdangdotcom.github.io/dubbox/rest.html


(1)   provider中添加自定义ExceptionMapperPOJO

package com.lee.test;

import com.alibaba.dubbo.rpc.RpcContext;

import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.core.Response.Status;
/**
 * Created by leedongwei on 15/10/19.
 */
@Provider
public class MyExceptionHandler implements ExceptionMapper<WebApplicationException>
{
    @Override
    public Response toResponse(WebApplicationException exception)
    {
        return Response.status(exception.getResponse().getStatus()).entity(new MyExceptionPOJO(exception.getMessage(), exception.getResponse().getStatus())).build();

    }
}


package com.lee.test;

import org.codehaus.jackson.annotate.JsonProperty;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;

/**
 * Created by leedongwei on 15/10/19.
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyExceptionPOJO implements Serializable {
    private String message ;
    private int code;
    public MyExceptionPOJO(String message,int code){
        this.message = message;
        this.code = code;

    }
    public String getMessage(){
        return this.message;
    }
    public int getCode(){
        return this.code;
    }
    public void setMessage(String message){
        this.message = message;
    }
    public void setCode(int code){
        this.code = code;
    }
    public MyExceptionPOJO(){

    }
}


(2)在provider的配置文件中增加配置:



    <dubbo:protocol name="rest" port="8888" threads="500" contextpath="services" server="tomcat" accepts="500"
                    extension="com.alibaba.dubbo.rpc.protocol.rest.support.LoggingFilter,
                    com.lee.test.MyExceptionHandler"
                    />

(3) provider 中的调用:


throw  new WebApplicationException("lee webA", Response.Status.CONFLICT);


(4)在consumer中增加解析,以java为例:

<span style="white-space:pre">	</span>Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Response response = target.request().get();
        String a = response.readEntity(String.class);


遇到的问题:

在浏览器中直接访问的时候报错:

application/octet-stream, was not found

在postman中访问无问题

解答:

http://stackoverflow.com/questions/7832760/a-message-body-writer-for-java-type-class-mypackage-b-and-mime-media-type-app?rq=1





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值