@ControllerAdvice异常处理程序方法未被调用

Vis*_*ngh 11 spring spring-mvc

我有以下控制器类

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();
    }
};
Run Code Online (Sandbox Code Playgroud)

}

对于异常处理,我使用的是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);
        }
Run Code Online (Sandbox Code Playgroud)

}

我已将XML bean定义定义为

<context:component-scan base-package="com.java.rest" />
Run Code Online (Sandbox Code Playgroud)

控制器通知处理程序不处理从控制器抛出的异常.我用谷歌搜索了几个小时,但找不到任何参考为什么会发生这种情况.我按照http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/所述进行了操作.

如果有人知道请告诉我为什么处理程序不处理异常.

Vis*_*ngh 11

我找到了上述问题的解决方案.实际上@ControllerAdvice需要XML文件中的MVC名称空间声明.或者我们可以将@EnableWebMvc与@ControllerAdvice注释一起使用.

  • 为了进一步明确这个答案,ResponseEntityExceptionHandler的子类必须包含在@ComponentScan的路径中,以便Spring容器检测它.我不认为文档对此非常清楚.希望这能节省一些人的时间. (3认同)

Cor*_*han -1

我认为问题可能是您的控制器方法抛出异常Exception,但您的@ControllerAdvice方法捕获了特定的异常。要么将它们组合成一个捕获 的处理程序Exception,要么让您的控制器抛出这些特定的异常。

所以你的控制器方法签名应该是:

public ResponseEntity redeemedVoucher(@RequestParam("voucherCode") String voucherCode) throws MethodArgumentNotValidException, ClassNotFoundException;
Run Code Online (Sandbox Code Playgroud)

或者你的控制器建议应该只有一种带注释的方法:

@ExceptionHandler({
    Exception.class
})
Run Code Online (Sandbox Code Playgroud)