12

次のコントローラークラスがあります

package com.java.rest.controllers;
@Controller
@RequestMapping("/api")
public class TestController {

@Autowired
private VoucherService voucherService;


@RequestMapping(value = "/redeemedVoucher", method = { RequestMethod.GET })
@ResponseBody
public ResponseEntity redeemedVoucher(@RequestParam("voucherCode") String voucherCode) throws Exception {
    if(voucherCode.equals( "" )){
        throw new MethodArgumentNotValidException(null, null);
    }
    Voucher voucher=voucherService.findVoucherByVoucherCode( voucherCode );
    if(voucher!= null){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        voucher.setStatus( "redeemed" );
        voucher.setAmount(new BigDecimal(0));
        voucherService.redeemedVoucher(voucher);
        return new ResponseEntity(voucher, headers, HttpStatus.OK);

    }
    else{
        throw new ClassNotFoundException();
    }
};

}

そして、例外処理のために、次のようにSpring3.2アドバイスハンドラーを使用しています

package com.java.rest.controllers;


@ControllerAdvice
public class VMSCenteralExceptionHandler extends ResponseEntityExceptionHandler{

@ExceptionHandler({
    MethodArgumentNotValidException.class
})
public ResponseEntity<String> handleValidationException( MethodArgumentNotValidException methodArgumentNotValidException ) {
    return new ResponseEntity<String>(HttpStatus.OK );
}

 @ExceptionHandler({ClassNotFoundException.class})
        protected ResponseEntity<Object> handleNotFound(ClassNotFoundException ex, WebRequest request) {
            String bodyOfResponse = "This Voucher is not found";
            return handleExceptionInternal(null, bodyOfResponse,
              new HttpHeaders(), HttpStatus.NOT_FOUND , request);
        }

}

XML Bean 定義を次のように定義しました

<context:component-scan base-package="com.java.rest" />

コントローラーからスローされた例外は、コントローラーのアドバイス ハンドラーによって処理されません。私は何時間もグーグルで検索しましたが、なぜそれが起こっているのかについての参照を見つけることができませんでした. ここでhttp://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/の説明に従ってフォローしました。

誰かが知っている場合は、ハンドラーが例外を処理しない理由を教えてください。

4

5 に答える 5

11

上記の問題の解決策を見つけました。実際に @ControllerAdvice は、XML ファイルで MVC 名前空間の宣言が必要です。または、 @ControllerAdvice アノテーションで @EnableWebMvc を使用できます。

于 2013-05-16T11:42:37.060 に答える
0

次の 2 つの手順を実行するだけです。

  1. グローバル例外ハンドラ クラスの上に@ControllerAdviceを追加します。
  2. component-scan ie に例外クラスのパッケージ名を追加します。

    <context:component-scan base-package="com.hr.controller,com.hr.exceptions" />

于 2016-11-23T10:32:54.853 に答える
-1

Exception問題はおそらく、コントローラーメソッドがスローするが、@ControllerAdviceメソッドが特定の例外をキャッチすることだと思います。それらを 1 つのハンドラーに結合して をキャッチExceptionするか、コントローラーにそれらの特定の例外をスローさせます。

したがって、コントローラーメソッドのシグネチャは次のようになります。

public ResponseEntity redeemedVoucher(@RequestParam("voucherCode") String voucherCode) throws MethodArgumentNotValidException, ClassNotFoundException;

または、コントローラーのアドバイスには、注釈を含むメソッドが 1 つだけ含まれている必要があります。

@ExceptionHandler({
    Exception.class
})
于 2013-05-16T08:37:18.123 に答える