借鉴:
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中添加自定义ExceptionMapper,POJO
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);
<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