如何在Spring REST中捕获CannotGetJdbcConnectionException

时间:2016-07-08 13:09:01

标签: java spring rest spring-mvc

我正在使用SpringOAuth创建一些RESTful Web服务。当数据库关闭时,框架中的某个地方CannotGetJdbcConnectionException - 当我在框架中的某个地方说,我的意思是它是在Spring代码中引起的,而不是在我编写的代码中引起的。我得到的REST响应是:

{
"timestamp": 1467982842783
"status": 500
"error": "Internal Server Error"
"exception": "org.springframework.jdbc.CannotGetJdbcConnectionException"
"message": "Could not get JDBC Connection; nested exception is java.sql.SQLException: Network error IOException: Connection refused: connect"
"path": "/1/test"
}

我尝试了很多东西。例如,我尝试创建一个扩展ResponseEntityExceptionHandler的类,如下所示:

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(CannotGetJdbcConnectionException.class)
    public ResponseEntity<String> handleNoConnection() {
        return new ResponseEntity<String>("Unable to connect to the database. Is it running?", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

但是方法handleNoConnection从未被捕获,实际上,基类(ResponseEntityExceptionHandler)中没有方法被调用 - 我在每个方法中都放置了断点。

我还尝试创建一个从BasicErrorController扩展的类,它确实在那里打破,但是没有Exception对象(它只作为字符串的类型名称存在)。例如:

@Controller
public class ErrorController extends BasicErrorController {

    public ErrorController() {
        super(new DefaultErrorAttributes());
    }   

    @Override public org.springframework.http.ResponseEntity<java.util.Map<String,Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    };

    @RequestMapping(
            value = {"${error.path:/error}"},
            produces = {"text/html"}
    )
    public ModelAndView errorHtml(HttpServletRequest request) {


        final HttpStatus status = getStatus(request);
        if (status == HttpStatus.UNAUTHORIZED) {
            return new ModelAndView("error401");
        } else if (status == HttpStatus.FORBIDDEN) {
            return new ModelAndView("error403");
        } else {
            return new ModelAndView("error500");
        }
    }

    public HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if(statusCode != null) {
            try {
                return HttpStatus.valueOf(statusCode.intValue());
            } catch (Exception e) {
            }
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}

我不确定还能做什么。正如我所说,我无法直接捕获异常,因为它发生在Spring代码本身。有没有其他方法可以捕获此异常?

0 个答案:

没有答案