下面列出了怎么用org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void handleNoSuchRequestHandlingMethod() {
NoSuchRequestHandlingMethodException ex = new NoSuchRequestHandlingMethodException(request);
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertNotNull("No ModelAndView returned", mav);
assertTrue("No Empty ModelAndView returned", mav.isEmpty());
assertEquals("Invalid status code", 404, response.getStatus());
}
@Test
public void shouldHandleException_should_return_not_found_error_when_passed_NoSuchRequestHandlingMethodException() {
// given
NoSuchRequestHandlingMethodException ex = new NoSuchRequestHandlingMethodException();
// when
ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);
// then
validateResponse(result, true, singletonList(testProjectApiErrors.getNotFoundApiError()));
}
@ExceptionHandler({ NoSuchRequestHandlingMethodException.class,
ConversionNotSupportedException.class })
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public String handleResourceNotFound(ModelMap model) {
model.put("advancedSearchData", new SearchData());
return "resourceNotFound";
}
@RequestMapping(method = RequestMethod.DELETE, path = "/greeting/{id}")
public void delete(@PathVariable Integer id)
throws NoSuchRequestHandlingMethodException {
try {
data.removeGreeting(id);
} catch (IndexOutOfBoundsException e) {
throw new NoSuchRequestHandlingMethodException("greeting",
GreetingController.class);
}
}
@RequestMapping(method = RequestMethod.PUT, path = "/greeting/{id}")
public Greeting add(@PathVariable Integer id,
@RequestBody Greeting greeting)
throws NoSuchRequestHandlingMethodException {
try {
return data.updateGreeting(id, greeting);
} catch (IndexOutOfBoundsException e) {
throw new NoSuchRequestHandlingMethodException("greeting",
GreetingController.class);
}
}
/**
* {@link NoSuchRequestHandlingMethodException}をハンドリングします。
* @param e {@link NoSuchRequestHandlingMethodException}
* @return {@link ErrorMessage}
* HTTPステータス 404 でレスポンスを返却します。
*/
@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@Override
public ErrorMessage handle(NoSuchRequestHandlingMethodException e) {
if (L.isDebugEnabled()) {
L.debug(R.getString("D-SPRINGMVC-REST-HANDLER#0001"), e);
}
ErrorMessage error = createClientErrorMessage(HttpStatus.NOT_FOUND);
warn(error, e);
return error;
}
@Test
public void NoSuchRequestHandlingMethodExceptionをハンドリングできる() {
NoSuchRequestHandlingMethodException ex = new NoSuchRequestHandlingMethodException("", "", null);
ErrorMessage message = this.exceptionHandlerSupport.handle(ex);
assertThat(message, notNullValue());
assertThat(message.getStatus(), is(404));
assertThat(message.getMessage(), is("リソースが見つかりません。"));
}
private Map<Class, RestExceptionHandler> getDefaultHandlers() {
Map<Class, RestExceptionHandler> map = new HashMap<>();
map.put( NoSuchRequestHandlingMethodException.class, new NoSuchRequestHandlingMethodExceptionHandler() );
map.put( HttpRequestMethodNotSupportedException.class, new HttpRequestMethodNotSupportedExceptionHandler() );
map.put( HttpMediaTypeNotSupportedException.class, new HttpMediaTypeNotSupportedExceptionHandler() );
map.put( MethodArgumentNotValidException.class, new MethodArgumentNotValidExceptionHandler() );
if (ClassUtils.isPresent("javax.validation.ConstraintViolationException", getClass().getClassLoader())) {
map.put( ConstraintViolationException.class, new ConstraintViolationExceptionHandler() );
}
addHandlerTo( map, HttpMediaTypeNotAcceptableException.class, NOT_ACCEPTABLE );
addHandlerTo( map, MissingServletRequestParameterException.class, BAD_REQUEST );
addHandlerTo( map, ServletRequestBindingException.class, BAD_REQUEST );
addHandlerTo( map, ConversionNotSupportedException.class, INTERNAL_SERVER_ERROR );
addHandlerTo( map, TypeMismatchException.class, BAD_REQUEST );
addHandlerTo( map, HttpMessageNotReadableException.class, UNPROCESSABLE_ENTITY );
addHandlerTo( map, HttpMessageNotWritableException.class, INTERNAL_SERVER_ERROR );
addHandlerTo( map, MissingServletRequestPartException.class, BAD_REQUEST );
addHandlerTo(map, Exception.class, INTERNAL_SERVER_ERROR);
// this class didn't exist before Spring 4.0
try {
Class clazz = Class.forName("org.springframework.web.servlet.NoHandlerFoundException");
addHandlerTo(map, clazz, NOT_FOUND);
} catch (ClassNotFoundException ex) {
// ignore
}
return map;
}
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
try {
if (ex instanceof NoSuchRequestHandlingMethodException) {
return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, request, response,
handler);
}
else if (ex instanceof HttpRequestMethodNotSupportedException) {
return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request,
response, handler);
}
else if (ex instanceof HttpMediaTypeNotSupportedException) {
return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, request, response,
handler);
}
else if (ex instanceof HttpMediaTypeNotAcceptableException) {
return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, request, response,
handler);
}
else if (ex instanceof MissingPathVariableException) {
return handleMissingPathVariable((MissingPathVariableException) ex, request,
response, handler);
}
else if (ex instanceof MissingServletRequestParameterException) {
return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, request,
response, handler);
}
else if (ex instanceof ServletRequestBindingException) {
return handleServletRequestBindingException((ServletRequestBindingException) ex, request, response,
handler);
}
else if (ex instanceof ConversionNotSupportedException) {
return handleConversionNotSupported((ConversionNotSupportedException) ex, request, response, handler);
}
else if (ex instanceof TypeMismatchException) {
return handleTypeMismatch((TypeMismatchException) ex, request, response, handler);
}
else if (ex instanceof HttpMessageNotReadableException) {
return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, request, response, handler);
}
else if (ex instanceof HttpMessageNotWritableException) {
return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, request, response, handler);
}
else if (ex instanceof MethodArgumentNotValidException) {
return handleMethodArgumentNotValidException((MethodArgumentNotValidException) ex, request, response,
handler);
}
else if (ex instanceof MissingServletRequestPartException) {
return handleMissingServletRequestPartException((MissingServletRequestPartException) ex, request,
response, handler);
}
else if (ex instanceof BindException) {
return handleBindException((BindException) ex, request, response, handler);
}
else if (ex instanceof NoHandlerFoundException) {
return handleNoHandlerFoundException((NoHandlerFoundException) ex, request, response, handler);
}
}
catch (Exception handlerException) {
if (logger.isWarnEnabled()) {
logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
}
}
return null;
}
@Test
public void noSuchRequestHandlingMethod() {
Exception ex = new NoSuchRequestHandlingMethodException("GET", TestController.class);
testException(ex);
}
@ExceptionHandler({ NoSuchRequestHandlingMethodException.class,
ConversionNotSupportedException.class })
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public String handleResourceNotFound() {
return "resourceNotFound";
}
@ExceptionHandler({NoSuchRequestHandlingMethodException.class, ConversionNotSupportedException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public String handleResourceNotFound(){
return "resourceNotFound";
}
@Override
public ResponseEntity<ErrorMessage> handleException(NoSuchRequestHandlingMethodException ex, HttpServletRequest req) {
LOG.warn(ex.getMessage());
return super.handleException(ex, req);
}
/**
* Handle the case where no request handler method was found.
* <p>The default implementation logs a warning, sends an HTTP 404 error, and returns
* an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen,
* or the NoSuchRequestHandlingMethodException could be rethrown as-is.
* @param ex the NoSuchRequestHandlingMethodException to be handled
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler, or {@code null} if none chosen
* at the time of the exception (for example, if multipart resolution failed)
* @return an empty ModelAndView indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protected ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
pageNotFoundLogger.warn(ex.getMessage());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return new ModelAndView();
}
/**
* Customize the response for NoSuchRequestHandlingMethodException.
* <p>This method logs a warning and delegates to {@link #handleExceptionInternal}.
* @param ex the exception
* @param headers the headers to be written to the response
* @param status the selected response status
* @param request the current request
* @return a {@code ResponseEntity} instance
*/
protected ResponseEntity<Object> handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
pageNotFoundLogger.warn(ex.getMessage());
return handleExceptionInternal(ex, null, headers, status, request);
}
/**
* {@link NoSuchRequestHandlingMethodException}をハンドリングします。
* @param e {@link NoSuchRequestHandlingMethodException}
* @return 任意の型
*/
T handle(NoSuchRequestHandlingMethodException e);