如何将控制器方法内生成的变量传递给ExceptionHandler

时间:2014-05-19 08:57:00

标签: spring

我需要将控制器方法内部生成的变量传递给异常处理程序。

变量是日志记录类,其中信息由变量服务类设置。

以下代码将解释我的意图。

@RequestMapping(value = "", method = RequestMethod.POST)
public @ResponseBody byte[] handleRequest(HttpServletRequest httpReq){
    CmpLog cmpLog = new CmpLog();
    cmpLog.setClient_ip(getClientIp(httpReq));
    ....
    testService.businessLogic(cmpLog);
    }



@ExceptionHandler(Exception.class)
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public @ResponseBody byte[] exceptionHandler(HttpServletRequest request, Exception e){

    // How do I somehow get the cmpLog in the above method?
    cmpLogService.create(cmpLog);
}

2 个答案:

答案 0 :(得分:3)

handleRequest内你可以做

httpReq.setAttribute("cmpLog", cmpLog )(在生成异常之前的某个地方)

,在exceptionHandler内你可以做

CmpLog cmpLog = (CmpLog)request.getAttribute("cmpLog")

答案 1 :(得分:2)

创建一个新的异常子类。将该值放入其中并在exceptionHandler中读取。

e.g。

class MyException extends Exception {
  private Object value;

  MyException(Object value) {
    this.value = value;
  }

  public Object getValue() {
    return value;
  }
}


@RequestMapping(value = "", method = RequestMethod.POST)
public @ResponseBody byte[] handleRequest(HttpServletRequest httpReq){
    CmpLog cmpLog = new CmpLog();
    cmpLog.setClient_ip(getClientIp(httpReq));
    ....
    testService.businessLogic(cmpLog);

    throw new MyException(someValue);
}



@ExceptionHandler(MyException.class)
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public @ResponseBody byte[] exceptionHandler(HttpServletRequest request, MyException e){

    // How do I somehow get the cmpLog in the above method?
    cmpLogService.create(cmpLog + e.getValue());
}