11

春のアプリケーションには 2 種類のコントローラーがあります。

  • ビューに転送して HTML を生成するビュー コントローラー
  • コントローラーから直接 JSON を返す API コントローラー

API コントローラーとビュー コントローラーはどちらも、同じ Spring ディスパッチャー サーブレットの一部です。Spring 3.2 では@ControllerAdvice、グローバルな場所で例外を処理できるようにするアノテーションが導入されました。

@ControllerAdviceドキュメントは、Dispatcher Servlet に関連付けられたすべてのコントローラーに適用されることを暗示しています。

どのコントローラ@ControllerAdviceが適用されるかを設定する方法はありますか?

たとえば、私のシナリオでは、View Controller用に を、API コントローラー用に@ControllerAdvice分離したいと考えています。@ControllerAdvice

4

5 に答える 5

3

I do not think this is possible now. If you can make the API and View controllers throw different Exception types, then you could define two different @ExceptionHandlers and achieve what you want.

// For handling API Exceptions
@ExceptionHandler(APIException.class)  // Single API Exception 
@ExceptionHandler({APIException.class, ..., ,,,}) // Multiple API Exceptions

// For handling View Exceptions
@ExceptionHandler(ViewException.class) // Single View Exception
@ExceptionHandler({ViewException.class, ..., ...}) // Multiple View Exceptions

You could use aop to translate the Exceptions coming out of APIs to a standard APIException. See this thread on spring forums.

Hope it helps.

于 2013-01-27T10:24:37.157 に答える
3

例外によって、応答のコンテンツ タイプが決まるべきではありません。代わりに、ブラウザが何を期待しているか、リクエストのAcceptヘッダーを確認してください。

@ExceptionHandler(Throwable.class)
public @ResponseBody String handleThrowable(HttpServletRequest request, HttpServletResponse response, Throwable ex) throws IOException {

...

String header = request.getHeader("Accept");

if(supportsJsonResponse(header)) {

    //return response as JSON
    response.setContentType(JSON_MEDIA_TYPE.toString());

    return Json.stringify(responseMap);

} else {
    //return as HTML
    response.setContentType("text/html");
}
于 2013-06-18T18:35:47.577 に答える
1
@ExceptionHandler(value=Exception.class)    
    public ModelAndView error(Exception ex) {                                
        return new ModelAndView("redirect:/error/m");                
    }

...//ErrorController

@RequestMapping(value = "/m", produces="text/html")
public ModelAndView error()...

@RequestMapping(value = "/m", produces="application/json")
@ResponseBody
public Map errorJson()...
于 2013-04-07T15:53:46.993 に答える