Vraptor e ExecuteMethodInterceptor

2 respostas
marcio89

Queria poder receber a exceção lançada por um método do meu @Resource e poder alterar o resultado enviado ao usuário.

Exemplo:

@NoTokenRequired
	@Path("/")
	public void index() throws ValidationException {
		throw new ValidationException(null);
	}

	@NoTokenRequired
	@Path("/1")
	public void index2() throws PersistenceException {
		throw new PersistenceException();
	}

A minha idéia seria um interceptador que pegasse essa exceção e descobrisse o tipo dela usando instanceOf e pudesse setar o resultado com os erros 400 ou 500.

public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) throws InterceptionException {
		try {
			stack.next(method, resourceInstance);
		} catch (Throwable e) {
			if (e instanceof ServiceException) {
				this.logger.warning("ERRO DE SERVICO");
			} else if (e instanceof ServerException) {
				this.logger.warning("ERRO DO SERVIDOR");
			}
		}
	}

Pelo que eu vi não tenho como fazer isso pois o ExecuteMethodInterceptor transforma minhas exceções em um InterceptionException.
É isso mesmo ?

2 Respostas

marcio89

Criei outro interceptor, depois de todos que faz …

try { stack.next(method, resourceInstance); } catch (InterceptionException ee) { Throwable t = ee.getCause(); if (t instanceof ServiceException) { this.logger.warning("ERRO DE SERVICO"); } else if (t instanceof ServerException) { this.logger.warning("ERRO DO SERVIDOR"); } }

Lógico que vou conferir se a cause é null etc.
Mas já resolve o que eu precisava. Alguém sugere algo melhor ?

Lucas_Cavalcanti

vc pode fazer algo do tipo:

try {
  stack.next(method, resourceInstance);
} catch (InterceptionException ee) {  
   try {
     throw ee.getCause();
   } catch (ServiceException e) {
      //...
   } catch (ServerException e) (
      //...
   } catch (Throwable e) {
      throw ee;
   }
}

Importante relançar a exception, senão a requisição continua normalmente ignorando o erro.

Criado 11 de julho de 2013
Ultima resposta 13 de jul. de 2013
Respostas 2
Participantes 2