2016-05-20 5 views
2

したがって、スプリングプロジェクトのコントローラから返された未知の例外はすべて一般的な方法でログに記録しようとしています。 は、私は次の例外ハンドラでこれを行うことができました:Spring例外ハンドラはすべての例外をログに記録しますが、元の応答を返します

@ControllerAdvice 
public class ControllerConfig { 

private final Logger logger = LoggerFactory.getLogger(this.getClass()); 

public static final String DEFAULT_ERROR_VIEW = "error"; 

@ExceptionHandler(HttpMessageNotReadableException.class) 
@ResponseStatus(HttpStatus.BAD_REQUEST) 
public void handleBadRequest(HttpMessageNotReadableException e) { 
    logger.warn("Returning HTTP 400 Bad Request", e); 
    throw e; 
} 

@ExceptionHandler(AccessDeniedException.class) 
public void defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception { 
    logger.error("Error in request:" + request.getRequestURL(), e); 
    throw e; 
} 

また、これは、要求のエラー応答を返すので、私はすべての異なるエラー応答コードを区別する必要はありません。

しかし、第2のエラーログが原因でメソッドでスローされた例外で作成されたメソッドの呼び出しごと: コードはorg.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#doResolveHandlerMethodException

からです
try { 
     if (logger.isDebugEnabled()) { 
      logger.debug("Invoking @ExceptionHandler method: " + exceptionHandlerMethod); 
     } 
     exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception); 
    } 
    catch (Exception invocationEx) { 
     if (logger.isErrorEnabled()) { 
      logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx); 
     } 
     return null; 
    } 

この方法の元の例外を返すスマートな方法はありますか?

答えて

0

「元の例外を返すよりスマートな方法」とは、どういう意味ですか。あなたは正確にクライアントに戻りたいと思いますか?これが例外のメッセージの場合は、例外ハンドラから返すだけで、@ResponseBodyというメソッドに注釈を付けることができます。春はあなたのために残りをします。

@ExceptionHandler(HttpMessageNotReadableException.class) 
@ResponseStatus(HttpStatus.BAD_REQUEST) 
@ResponseBody 
public String handleBadRequest(HttpMessageNotReadableException e) { 
    logger.warn("Returning HTTP 400 Bad Request", e); 
    throw e.getMessage(); 
} 

例外情報と希望する他のデータをラップするカスタムオブジェクトを返すこともできます。

関連する問題