users@jersey.java.net

[Jersey] Re: ExceptionMapper and the request

From: douguoqiang <douguoqiang_at_ejianlong.com>
Date: Thu, 31 Jan 2013 08:57:46 +0800

Hi,

You can you @Context, example:
@Provider
public class ExceptionMapperSupport implements ExceptionMapper {
        private static final Logger LOGGER = Logger
                        .getLogger(ExceptionMapperSupport.class);

        private static final String CONTEXT_ATTRIBUTE = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;

        @Context
        private HttpServletRequest request;

        @Context
        private ServletContext servletContext;

        /**
         * 异常处理
         *
         * @param exception
         * @return 异常处理后的Response对象
         */
        public Response toResponse(Exception exception) {
                String message = "Internal Server Error";
                Status statusCode = Status.INTERNAL_SERVER_ERROR;
                WebApplicationContext context = (WebApplicationContext) servletContext
                                .getAttribute(CONTEXT_ATTRIBUTE);
                if (exception instanceof BaseException) {
                        BaseException baseException = (BaseException) exception;
                        String code = baseException.getCode();
                        Object[] args = baseException.getValues();
                        message = context.getMessage(code, args, exception.getMessage(),
                                        request.getLocale());
                        
                } else if (exception instanceof NotFoundException) {
                        message = "Request Not Found";
                        statusCode = Status.NOT_FOUND;
                } else if (exception instanceof WebApplicationException) {
                        //WebApplicationException类异常直接由对应的异常定义返回的消息
                        LOGGER.error(message, exception);
                        WebApplicationException webAppException = (WebApplicationException) exception;
                        return webAppException.getResponse();
                } else {
                        message = context.getMessage(exception.getMessage(), null, message,
                                        request.getLocale());
                }
                LOGGER.error(message, exception);
                return Response.ok(message, MediaType.TEXT_PLAIN).status(statusCode)
                                .build();
        }
}





douguoqiang

From: Craig Ching
Date: 2013-01-31 00:01
To: users
Subject: [Jersey] ExceptionMapper and the request
Hi!


Is there anyway in an ExceptionMapper to get the original request? I was thinking that for an Accepts header of application/json I would return a JSON response but for an Accepts of text/html I would redirect to our main page. Any other way I might accomplish that?


Cheers,

Craig