Jersey Exception Handling
使用JERSEY框架输出JSON,需捕获所有的HTTP错误,如404等,业务错误及其他未定义的错误,将这些错误输出JSON,而不是TOMCAT的错误。JERSEY已和SPRING整合。
web.xml
<?
xml version="1.0" encoding="UTF-8"
?>
< web-app xmlns ="http://java.sun.com/xml/ns/javaee" >
< display-name >Restful Web Application </ display-name >
< servlet >
< servlet-name >jersey-serlvet </ servlet-name >
< servlet-class >
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</ servlet-class >
< init-param >
< param-name >com.sun.jersey.config.property.packages </ param-name >
< param-value >restfullapi.rest.service,restfullapi.common.provider,restful.web </ param-value >
</ init-param >
< init-param >
< param-name >com.sun.jersey.api.json.POJOMappingFeature </ param-name >
< param-value >true </ param-value >
</ init-param >
< load-on-startup >2 </ load-on-startup >
</ servlet >
< servlet-mapping >
< servlet-name >jersey-serlvet </ servlet-name >
< url-pattern >/* </ url-pattern >
</ servlet-mapping >
< listener >
< listener-class >
org.springframework.web.context.ContextLoaderListener
</ listener-class >
</ listener >
< listener >
< listener-class >
org.springframework.web.context.request.RequestContextListener
</ listener-class >
</ listener >
< context-param >
< param-name >contextConfigLocation </ param-name >
< param-value >/WEB-INF/mvc-dispatcher-servlet.xml </ param-value >
</ context-param >
<!-- spring logback -->
< context-param >
< param-name >logbackConfigLocation </ param-name >
< param-value >classpath:logback.xml </ param-value >
</ context-param >
< listener >
< listener-class >ch.qos.logback.ext.spring.web.LogbackConfigListener </ listener-class >
</ listener >
< context-param >
< param-name >webAppRootKey </ param-name >
< param-value >restfull-api </ param-value >
</ context-param >
< welcome-file-list >
< welcome-file >/index.jsp </ welcome-file >
</ welcome-file-list >
</ web-app >
< web-app xmlns ="http://java.sun.com/xml/ns/javaee" >
< display-name >Restful Web Application </ display-name >
< servlet >
< servlet-name >jersey-serlvet </ servlet-name >
< servlet-class >
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</ servlet-class >
< init-param >
< param-name >com.sun.jersey.config.property.packages </ param-name >
< param-value >restfullapi.rest.service,restfullapi.common.provider,restful.web </ param-value >
</ init-param >
< init-param >
< param-name >com.sun.jersey.api.json.POJOMappingFeature </ param-name >
< param-value >true </ param-value >
</ init-param >
< load-on-startup >2 </ load-on-startup >
</ servlet >
< servlet-mapping >
< servlet-name >jersey-serlvet </ servlet-name >
< url-pattern >/* </ url-pattern >
</ servlet-mapping >
< listener >
< listener-class >
org.springframework.web.context.ContextLoaderListener
</ listener-class >
</ listener >
< listener >
< listener-class >
org.springframework.web.context.request.RequestContextListener
</ listener-class >
</ listener >
< context-param >
< param-name >contextConfigLocation </ param-name >
< param-value >/WEB-INF/mvc-dispatcher-servlet.xml </ param-value >
</ context-param >
<!-- spring logback -->
< context-param >
< param-name >logbackConfigLocation </ param-name >
< param-value >classpath:logback.xml </ param-value >
</ context-param >
< listener >
< listener-class >ch.qos.logback.ext.spring.web.LogbackConfigListener </ listener-class >
</ listener >
< context-param >
< param-name >webAppRootKey </ param-name >
< param-value >restfull-api </ param-value >
</ context-param >
< welcome-file-list >
< welcome-file >/index.jsp </ welcome-file >
</ welcome-file-list >
</ web-app >
AbstractBaseRestfulException.java
public
abstract
class AbstractBaseRestfulException
extends Exception{
private static final long serialVersionUID = 6779508767332777451L;
public AbstractBaseRestfulException()
{
}
public AbstractBaseRestfulException(String message)
{
super(message);
}
public abstract String getErrcode();
public abstract void setErrcode(String errcode);
public abstract String getDescription();
public abstract void setDescription(String description);
}
private static final long serialVersionUID = 6779508767332777451L;
public AbstractBaseRestfulException()
{
}
public AbstractBaseRestfulException(String message)
{
super(message);
}
public abstract String getErrcode();
public abstract void setErrcode(String errcode);
public abstract String getDescription();
public abstract void setDescription(String description);
}
AbstractBaseRestfulExceptionMapper.java
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.paul.common.exception.AbstractBaseRestfulException;
import com.paul.common.json.DefaultJsonResponse;
@Provider
public class AbstractBaseRestfulExceptionMapper implements ExceptionMapper<AbstractBaseRestfulException>{
private Logger logger = LoggerFactory.getLogger(AbstractBaseRestfulExceptionMapper. class);
public Response toResponse(AbstractBaseRestfulException exception) {
logger.error(exception.getMessage(), exception);
DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
response.setDescription(exception.getDescription());
response.setErrcode(exception.getErrcode());
response.setResult( null);
return Response.status(Status.BAD_REQUEST)
.entity(response)
.type(MediaType.APPLICATION_JSON + ";charset=utf-8")
.build();
}
}
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.paul.common.exception.AbstractBaseRestfulException;
import com.paul.common.json.DefaultJsonResponse;
@Provider
public class AbstractBaseRestfulExceptionMapper implements ExceptionMapper<AbstractBaseRestfulException>{
private Logger logger = LoggerFactory.getLogger(AbstractBaseRestfulExceptionMapper. class);
public Response toResponse(AbstractBaseRestfulException exception) {
logger.error(exception.getMessage(), exception);
DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
response.setDescription(exception.getDescription());
response.setErrcode(exception.getErrcode());
response.setResult( null);
return Response.status(Status.BAD_REQUEST)
.entity(response)
.type(MediaType.APPLICATION_JSON + ";charset=utf-8")
.build();
}
}
OtherExceptionMapper.java
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.paul.common.json.DefaultJsonResponse;
import com.paul.common.json.JsonResponseStatus;
@Provider
public class OtherExceptionMapper implements ExceptionMapper<Exception>{
private Logger logger = LoggerFactory.getLogger(OtherExceptionMapper. class);
public Response toResponse(Exception exception) {
logger.error(exception.getMessage(), exception);
DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
response.setDescription(JsonResponseStatus.OTHER_ERROR.getMessage() + exception.getMessage());
response.setErrcode(JsonResponseStatus.OTHER_ERROR.getCode());
response.setResult( null);
return Response.status(Status.BAD_REQUEST)
.entity(response)
.type(MediaType.APPLICATION_JSON + ";charset=utf-8")
.build();
}
}
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.paul.common.json.DefaultJsonResponse;
import com.paul.common.json.JsonResponseStatus;
@Provider
public class OtherExceptionMapper implements ExceptionMapper<Exception>{
private Logger logger = LoggerFactory.getLogger(OtherExceptionMapper. class);
public Response toResponse(Exception exception) {
logger.error(exception.getMessage(), exception);
DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
response.setDescription(JsonResponseStatus.OTHER_ERROR.getMessage() + exception.getMessage());
response.setErrcode(JsonResponseStatus.OTHER_ERROR.getCode());
response.setResult( null);
return Response.status(Status.BAD_REQUEST)
.entity(response)
.type(MediaType.APPLICATION_JSON + ";charset=utf-8")
.build();
}
}
WebApplicationExceptionMapper.java
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.paul.common.json.DefaultJsonResponse;
@Provider
public class WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException >{
private Logger logger = LoggerFactory.getLogger(WebApplicationExceptionMapper. class);
public Response toResponse(WebApplicationException exception) {
logger.error(exception.getMessage(), exception);
DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
response.setDescription(exception.getMessage());
response.setErrcode(String.valueOf(exception.getResponse().getStatus()));
response.setResult( null);
return Response.status(exception.getResponse().getStatus())
.entity(response)
.type(MediaType.APPLICATION_JSON + ";charset=utf-8")
.build();
}
}
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.paul.common.json.DefaultJsonResponse;
@Provider
public class WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException >{
private Logger logger = LoggerFactory.getLogger(WebApplicationExceptionMapper. class);
public Response toResponse(WebApplicationException exception) {
logger.error(exception.getMessage(), exception);
DefaultJsonResponse<Object> response = new DefaultJsonResponse<Object>();
response.setDescription(exception.getMessage());
response.setErrcode(String.valueOf(exception.getResponse().getStatus()));
response.setResult( null);
return Response.status(exception.getResponse().getStatus())
.entity(response)
.type(MediaType.APPLICATION_JSON + ";charset=utf-8")
.build();
}
}
Controller中无须再处理异常
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.paul.common.json.DefaultJsonResponse;
import com.paul.common.json.JsonResponseStatus;
import com.paul.program.stbstart.valueobject.StbStart;
import com.paul.stbstart.valueobject.StbStartRequest;
import com.paul.restfullapi.rest.service.AdvertisementRestfulService;
@Path("/advertisement")
@Controller
public class AdvertisementRestfulController {
private Logger logger = LoggerFactory.getLogger(AdvertisementRestfulController. class);
@Autowired
AdvertisementRestfulService advertisementRestfulService;
@Path("/getAdvertisement")
@Produces({MediaType.APPLICATION_JSON + ";charset=utf-8"})
@GET
public DefaultJsonResponse<StbStart> getAdvertisement(
@DefaultValue("") @QueryParam("version")String version,
@QueryParam("token")String token) throws Exception
{
DefaultJsonResponse<StbStart> response = new DefaultJsonResponse<StbStart>();
StbStartRequest request = new StbStartRequest();
logger.info(version);
request.setVersion(version);
request.setToken(token);
StbStart result = advertisementRestfulService.findByVersion(request);
response.setResult(result);
response.setDescription(JsonResponseStatus.SUCCESS.getMessage());
response.setErrcode(JsonResponseStatus.SUCCESS.getCode());
logger.info("----------------");
// double i = 1/0;
return response;
}
}
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.paul.common.json.DefaultJsonResponse;
import com.paul.common.json.JsonResponseStatus;
import com.paul.program.stbstart.valueobject.StbStart;
import com.paul.stbstart.valueobject.StbStartRequest;
import com.paul.restfullapi.rest.service.AdvertisementRestfulService;
@Path("/advertisement")
@Controller
public class AdvertisementRestfulController {
private Logger logger = LoggerFactory.getLogger(AdvertisementRestfulController. class);
@Autowired
AdvertisementRestfulService advertisementRestfulService;
@Path("/getAdvertisement")
@Produces({MediaType.APPLICATION_JSON + ";charset=utf-8"})
@GET
public DefaultJsonResponse<StbStart> getAdvertisement(
@DefaultValue("") @QueryParam("version")String version,
@QueryParam("token")String token) throws Exception
{
DefaultJsonResponse<StbStart> response = new DefaultJsonResponse<StbStart>();
StbStartRequest request = new StbStartRequest();
logger.info(version);
request.setVersion(version);
request.setToken(token);
StbStart result = advertisementRestfulService.findByVersion(request);
response.setResult(result);
response.setDescription(JsonResponseStatus.SUCCESS.getMessage());
response.setErrcode(JsonResponseStatus.SUCCESS.getCode());
logger.info("----------------");
// double i = 1/0;
return response;
}
}