users@jersey.java.net

[Jersey] Re: ExceptionMapper and the request

From: Craig Ching <craigching_at_gmail.com>
Date: Thu, 31 Jan 2013 16:32:01 -0600

Thanks for both of your responses, works perfectly as advertised!

Cheers,
Craig


On Wed, Jan 30, 2013 at 6:57 PM, douguoqiang <douguoqiang_at_ejianlong.com>wrote:

> **
> 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 <craigching_at_gmail.com>
> *Date:* 2013-01-31 00:01
> *To:* users <users_at_jersey.java.net>
> *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
>