Java 类org.springframework.web.servlet.NoHandlerFoundException 实例源码

项目:blcdemo    文件:BroadleafSpringRestExceptionMapper.java   
@ExceptionHandler(NoHandlerFoundException.class)
public @ResponseBody ErrorWrapper handleNoHandlerFoundException(HttpServletRequest request, HttpServletResponse response, Exception ex){
    ErrorWrapper errorWrapper = (ErrorWrapper) context.getBean(ErrorWrapper.class.getName());
    Locale locale = null;
    BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext();
    if (requestContext != null) {
        locale = requestContext.getJavaLocale();
    }

    LOG.error("An error occured invoking a REST service", ex);
    if (locale == null) {
        locale = Locale.getDefault();
    }
    errorWrapper.setHttpStatusCode(HttpStatus.SC_NOT_FOUND);
    response.setStatus(resolveResponseStatusCode(ex, errorWrapper));
    ErrorMessageWrapper errorMessageWrapper = (ErrorMessageWrapper) context.getBean(ErrorMessageWrapper.class.getName());
    errorMessageWrapper.setMessageKey(resolveClientMessageKey(BroadleafWebServicesException.NOT_FOUND));
    errorMessageWrapper.setMessage(messageSource.getMessage(BroadleafWebServicesException.NOT_FOUND, null,
            BroadleafWebServicesException.NOT_FOUND, locale));
    errorWrapper.getMessages().add(errorMessageWrapper);

    return errorWrapper;
}
项目:jmzTab-m    文件:ValidationController.java   
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handleUnmapped(HttpServletRequest req) {
    ModelAndView mav = new ModelAndView();
    mav.addObject("page", new Page("mzTabValidator", versionNumber, gaId));
    mav.addObject("error", "Resource not found!");
    mav.addObject("url", req.getRequestURL());
    mav.addObject("timestamp", new Date().toString());
    mav.addObject("status", 404);
    mav.setViewName("error");
    return mav;
}
项目:miaohu    文件:GlobalExceptionAdvice.java   
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String,String> requestHandlingNoHandlerFound() {
    Map message = new HashMap();
    message.put("error","router is not exists");
    return message;
}
项目:pingguopai    文件:WebMvcConfigurer.java   
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    exceptionResolvers.add(new HandlerExceptionResolver() {
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
            Result result = new Result();
            logger.warn(e.getMessage());
            if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误”
                result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
            } else if (e instanceof IllegalArgumentException) {  //参数检查异常
                result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
            }else if (e instanceof NoHandlerFoundException) {
                result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在");
            } else if (e instanceof ServletException) {
                result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
            } else  if (e instanceof AccessDeniedException){
                result.setCode(ResultCode.PERMIT).setMessage(e.getMessage());
            } else {
                result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员");
                String message;
                if (handler instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s",
                            request.getRequestURI(),
                            handlerMethod.getBean().getClass().getName(),
                            handlerMethod.getMethod().getName(),
                            e.getMessage());
                } else {
                    message = e.getMessage();
                }
                logger.error(message, e);
            }
            responseResult(response, result);
            return new ModelAndView();
        }

    });
}
项目:SpringBootStudy    文件:WebMvcConfig.java   
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    exceptionResolvers.add(new HandlerExceptionResolver() {
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
            Result result = new Result();
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;

                if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误”
                    result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
                    logger.info(e.getMessage());
                } else {
                    result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员");
                    String message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s",
                            request.getRequestURI(),
                            handlerMethod.getBean().getClass().getName(),
                            handlerMethod.getMethod().getName(),
                            e.getMessage());
                    logger.error(message, e);
                }
            } else {
                if (e instanceof NoHandlerFoundException) {
                    result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在");
                } else {
                    result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage(e.getMessage());
                    logger.error(e.getMessage(), e);
                }
            }
            responseResult(response, result);
            return new ModelAndView();
        }

    });
}
项目:SpringBootStudy    文件:WebMvcConfig.java   
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    exceptionResolvers.add(new HandlerExceptionResolver() {
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
            Result result = new Result();
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;

                if (e instanceof ServiceException) {//业务失败的异常,如“账号或密码错误”
                    result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
                    logger.info(e.getMessage());
                } else {
                    result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误,请联系管理员");
                    String message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s",
                            request.getRequestURI(),
                            handlerMethod.getBean().getClass().getName(),
                            handlerMethod.getMethod().getName(),
                            e.getMessage());
                    logger.error(message, e);
                }
            } else {
                if (e instanceof NoHandlerFoundException) {
                    result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在");
                } else {
                    result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage(e.getMessage());
                    logger.error(e.getMessage(), e);
                }
            }
            responseResult(response, result);
            return new ModelAndView();
        }

    });
}
项目:xxproject    文件:CustomRestExceptionHandler.java   
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(final NoHandlerFoundException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = "No handler found for " + ex.getHttpMethod() + " " + ex.getRequestURL();

    final ApiError apiError = new ApiError(HttpStatus.NOT_FOUND, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
项目:AntiSocial-Platform    文件:ExceptionController.java   
/**
 * Exception Controller.
 * Catches various exceptions thrown throughout the application runtime.
 *
 * @author Ant Kaynak - Github/Exercon
 */

@ExceptionHandler(NoHandlerFoundException.class)
public String handleError404(Exception e , RedirectAttributes attr)   {
        attr.addFlashAttribute("error","Requested page does not exist!");
        return "redirect:/error";
}
项目:AntiSocial-Platform    文件:ExceptionController.java   
/**
 * Exception Controller.
 * Catches various exceptions thrown throughout the application runtime.
 *
 * @author Ant Kaynak - Github/Exercon
 */

@ExceptionHandler(NoHandlerFoundException.class)
public String handleError404(Exception e , RedirectAttributes attr)   {
    e.printStackTrace();
        attr.addFlashAttribute("error","Requested page does not exist!");
        return "redirect:/oups";
}
项目:project-template    文件:GlobalErrorHandlers.java   
@ResponseStatus(code = HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public ErrorDto handleNoHandlerFoundException(NoHandlerFoundException ex) {
    return ErrorDto.builder()
            .errorCode(ErrorCodes.NOT_FOUND)
            .message(ex.getLocalizedMessage())
            .build();
}
项目:ait-platform    文件:AitRestExceptionHandler.java   
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(final NoHandlerFoundException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = "No handler found for " + ex.getHttpMethod() + " " + ex.getRequestURL();

    final AitException AitException = new AitException(HttpStatus.NOT_FOUND, ex.getLocalizedMessage(), error);
    return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request);
}
项目:shootmimi    文件:GlobalExceptionHandler.java   
@ExceptionHandler(value = NoHandlerFoundException.class)
public ModelAndView defaultNotFoundHandler(HttpServletRequest req, Exception e) throws Exception {
    e.printStackTrace();
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", e);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("/404");
    return mav;
}
项目:spring4-understanding    文件:DefaultHandlerExceptionResolverTests.java   
@Test
public void handleNoHandlerFoundException() throws Exception {
    ServletServerHttpRequest req = new ServletServerHttpRequest(
            new MockHttpServletRequest("GET","/resource"));
    NoHandlerFoundException ex = new NoHandlerFoundException(req.getMethod().name(),
            req.getServletRequest().getRequestURI(),req.getHeaders());
    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());
}
项目:spring4-understanding    文件:ResponseEntityExceptionHandlerTests.java   
@Test
public void noHandlerFoundException() {
    ServletServerHttpRequest req = new ServletServerHttpRequest(
            new MockHttpServletRequest("GET","/resource"));
    Exception ex = new NoHandlerFoundException(req.getMethod().toString(),
            req.getServletRequest().getRequestURI(),req.getHeaders());
    testException(ex);
}
项目:OHMS    文件:HMSRestExceptionHandler.java   
@ExceptionHandler( NoHandlerFoundException.class )
@ResponseStatus( value = HttpStatus.BAD_REQUEST )
@ResponseBody
public BaseResponse hmsException( HttpServletRequest req, NoHandlerFoundException exception )
{

    return new BaseResponse( HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(),
                             exception.getMessage() );
}
项目:backstopper    文件:OneOffSpringFrameworkExceptionHandlerListenerTest.java   
@Test
public void shouldHandleException_should_return_not_found_error_when_passed_NoHandlerFoundException() {
    // given
    NoHandlerFoundException ex = new NoHandlerFoundException("GET", "/some/url", mock(HttpHeaders.class));

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    validateResponse(result, true, Collections.singletonList(testProjectApiErrors.getNotFoundApiError()));
}
项目:entelect-spring-webapp-template    文件:GlobalExceptionControllerAdvice.java   
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handle404(NoHandlerFoundException ex,
                              HttpServletRequest request) {
    log.error(String.format("URL %s. was not found and caused an exception", request.getRequestURL()));

    return new ModelAndView("forward:/404");
}
项目:summer    文件:WebAppExceptionAdvice.java   
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public State handlerNotFoundException(HttpServletRequest req, NoHandlerFoundException ex) {
    logger.error("NoHandlerFoundException:{}", ex);
    String errorURL = req.getRequestURL().toString();
    return new State(HttpStatus.NOT_FOUND.value() * 10, "Not found this url:".concat(errorURL));
}
项目:dawg    文件:AdminController.java   
@RequestMapping(value="/user/{userId}", method = { RequestMethod.PUT } )
@ResponseBody
public void createUser(@PathVariable String userId, @RequestBody DawgUserAndRoles user) throws UserException, NoHandlerFoundException {
    if (userService == null) throw new NoHandlerFoundException(RequestMethod.PUT.name(), "/user/" + userId, null);
    user.setUid(userId);
    userService.addUser(user, user.getRoles());
}
项目:dawg    文件:AdminController.java   
@RequestMapping(value="/user/{userId}", method = { RequestMethod.POST } )
@ResponseBody
public void modifyUser(@PathVariable String userId, @RequestBody DawgUser modifications) throws UserException, NoHandlerFoundException {
    if (userService == null) throw new NoHandlerFoundException(RequestMethod.POST.name(), "/user/" + userId, null);
    modifications.setUid(userId);
    userService.modifyUser(modifications);
}
项目:problem-spring-web    文件:AdviceTraitLoggingTest.java   
@ParameterizedTest
@MethodSource("data")
void shouldLog4xxAsWarn(final Status status) {
    assumeTrue(status.getStatusCode() / 100 == 4);
    unit.create(status, new NoHandlerFoundException("GET", "/", new HttpHeaders()), mock(NativeWebRequest.class));

    final LoggingEvent event = getOnlyElement(log.getLoggingEvents());
    assertThat(event.getLevel(), is(Level.WARN));
    assertThat(event.getMessage(), is("{}: {}"));
    assertThat(event.getArguments(), contains(getReasonPhrase(status), "No handler found for GET /"));
    assertThat(event.getThrowable().orNull(), is(nullValue()));
}
项目:dss-demonstrations    文件:GlobalExceptionHandler.java   
@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handle(HttpServletRequest req, Exception e) {
    return getMAV(req, e, HttpStatus.NOT_FOUND);
}
项目:spring-boot-boilerplate    文件:GlobalExceptionHandler.java   
@ExceptionHandler(value = { NoHandlerFoundException.class })
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public String noHandlerFoundException(Exception ex) {
    return  HttpStatus.NOT_FOUND.value()+ "没找到"+ HttpStatus.NOT_FOUND.getReasonPhrase() ;
}
项目:JuniperBotJ    文件:GlobalExceptionHandler.java   
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleExceptiond(NoHandlerFoundException ex) {
    return "error404";
}
项目:QRcode-factory    文件:AdviceController.java   
@ExceptionHandler(NoHandlerFoundException.class)
public String handleNotFound(Exception ex) {
    return "redirect:/404";
}
项目:errorest-spring-boot-starter    文件:ErrorDataProviderContext.java   
public <T extends Throwable> ErrorDataProvider getErrorDataProvider(T ex) {
    if (ex instanceof ApplicationException) {
        return new ApplicationErrorDataProvider(errorestProperties);
    }
    if (ex instanceof ExternalHttpRequestException) {
        return new ExternalHttpRequestErrorDataProvider(errorestProperties);
    }
    if (ex instanceof BindException) {
        return new BindExceptionErrorDataProvider(errorestProperties);
    }
    if (ex instanceof MethodArgumentNotValidException) {
        return new MethodArgumentNotValidErrorDataProvider(errorestProperties);
    }
    if (ex instanceof HttpMediaTypeNotAcceptableException) {
        return new MediaTypeNotAcceptableErrorDataProvider(errorestProperties);
    }
    if (ex instanceof HttpMediaTypeNotSupportedException) {
        return new MediaTypeNotSupportedErrorDataProvider(errorestProperties);
    }
    if (ex instanceof HttpRequestMethodNotSupportedException) {
        return new RequestMethodNotSupportedErrorDataProvider(errorestProperties);
    }
    if (ex instanceof MissingServletRequestParameterException) {
        return new MissingServletRequestParameterErrorDataProvider(errorestProperties);
    }
    if (ex instanceof HttpMessageNotReadableException) {
        return new MessageNotReadableErrorDataProvider(errorestProperties);
    }
    if (ex instanceof MissingServletRequestPartException) {
        return new MissingServletRequestPartErrorDataProvider(errorestProperties);
    }
    if (ex instanceof NoHandlerFoundException) {
        return new NoHandlerFoundErrorDataProvider(errorestProperties);
    }
    if (ex instanceof ServletRequestBindingException) {
        return new ServletRequestBindingErrorDataProvider(errorestProperties);
    }
    if (ex instanceof TypeMismatchException) {
        return new TypeMismatchErrorDataProvider(errorestProperties);
    }
    return new ThrowableErrorDataProvider(errorestProperties);
}
项目:errorest-spring-boot-starter    文件:NoHandlerFoundErrorDataProvider.java   
@Override
public ErrorData getErrorData(NoHandlerFoundException ex, HttpServletRequest request) {
    return getErrorData(ex, request, NOT_FOUND);
}
项目:errorest-spring-boot-starter    文件:NoHandlerFoundErrorDataProvider.java   
@Override
public ErrorData getErrorData(NoHandlerFoundException ex, HttpServletRequest request, HttpStatus responseHttpStatus, ErrorAttributes errorAttributes, RequestAttributes requestAttributes) {
    return super.getErrorData(ex, request, NOT_FOUND, errorAttributes, requestAttributes);
}
项目:errorest-spring-boot-starter    文件:NoHandlerFoundErrorDataProvider.java   
@Override
protected String getErrorDescription(NoHandlerFoundException ex) {
    return NOT_FOUND.getReasonPhrase() + ", " + uncapitalize(ex.getMessage());
}
项目:errorest-spring-boot-starter    文件:ServletFilter.java   
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (!requestMatcher.matches(request)) {
        filterChain.doFilter(request, response);
        return;
    }
    String uri = request.getRequestURI();
    if (uri.endsWith("/exception")) {
        throw new RuntimeException("Exception from servlet filer");
    }
    if (uri.endsWith("/media-type-not-acceptable")) {
        throw new HttpMediaTypeNotAcceptableException(asList(APPLICATION_JSON, APPLICATION_XML));
    }
    if (uri.endsWith("/media-type-not-supported")) {
        throw new HttpMediaTypeNotSupportedException(TEXT_HTML, singletonList(TEXT_PLAIN));
    }
    if (uri.endsWith("/message-not-readable")) {
        throw new HttpMessageNotReadableException("Message not readable from servlet filter");
    }
    if (uri.endsWith("/missing-servlet-request-parameter")) {
        throw new MissingServletRequestParameterException("query-parameter", "String");
    }
    if (uri.endsWith("/missing-servlet-request-part")) {
        throw new MissingServletRequestPartException("part");
    }
    if (uri.endsWith("/no-handler-found")) {
        throw new NoHandlerFoundException(request.getMethod(), request.getRequestURI(), null);
    }
    if (uri.endsWith("/request-method-not-supported")) {
        throw new HttpRequestMethodNotSupportedException(request.getMethod(), singletonList("DELETE"));
    }
    if (uri.endsWith("/servlet-request-binding")) {
        throw new ServletRequestBindingException("Exception from servlet filter");
    }
    if (uri.endsWith("/type-mismatch")) {
        String parameter = request.getParameter("query-parameter");
        NumberFormatException ex = new NumberFormatException("For input string: \"" + parameter + "\"");
        throw new MethodArgumentTypeMismatchException(parameter, int.class, null, null, ex);
    }
    if (uri.endsWith("/application")) {
        throw new TestApplicationException();
    }
    if (uri.endsWith("/external-request")) {
        rest.getForObject("http://localhost:10000/external/resource", String.class);
    }
    if (uri.endsWith("/access-denied")) {
        throw new AccessDeniedException("Access denied from servlet filter");
    }
    if (uri.endsWith("/authentication-error")) {
        throw new BadCredentialsException("Access denied from servlet filter");
    }
    if (uri.endsWith("/no-error")) {
        prepareResponse(request, response);
    } else {
        filterChain.doFilter(request, response);
    }
}
项目:spring4-understanding    文件:DefaultHandlerExceptionResolver.java   
@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;
}
项目:easy-mybatis    文件:RestExceptionHandler.java   
@ExceptionHandler({NoSuchRequestHandlingMethodException.class,
        HttpRequestMethodNotSupportedException.class,
        HttpMediaTypeNotSupportedException.class,
        HttpMediaTypeNotAcceptableException.class,
        MissingServletRequestParameterException.class,
        ServletRequestBindingException.class,
        ConversionNotSupportedException.class,
        TypeMismatchException.class,
        HttpMessageNotReadableException.class,
        HttpMessageNotWritableException.class,
        MethodArgumentNotValidException.class,
        MissingServletRequestPartException.class,
        BindException.class,
        NoHandlerFoundException.class})
public final ResponseEntity<Object> handleException(Exception ex, HttpServletRequest request) {
    HttpHeaders headers = new HttpHeaders();
    HttpStatus status;
    if(ex instanceof NoSuchRequestHandlingMethodException) {
        status = HttpStatus.NOT_FOUND;
        return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException)ex, headers, status, request);
    } else if(ex instanceof HttpRequestMethodNotSupportedException) {
        status = HttpStatus.METHOD_NOT_ALLOWED;
        return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException)ex, headers, status, request);
    } else if(ex instanceof HttpMediaTypeNotSupportedException) {
        status = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
        return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException)ex, headers, status, request);
    } else if(ex instanceof HttpMediaTypeNotAcceptableException) {
        status = HttpStatus.NOT_ACCEPTABLE;
        return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException)ex, headers, status, request);
    } else if(ex instanceof MissingServletRequestParameterException) {
        status = HttpStatus.BAD_REQUEST;
        return handleMissingServletRequestParameter((MissingServletRequestParameterException)ex, headers, status, request);
    } else if(ex instanceof ServletRequestBindingException) {
        status = HttpStatus.BAD_REQUEST;
        return handleServletRequestBindingException((ServletRequestBindingException)ex, headers, status, request);
    } else if(ex instanceof ConversionNotSupportedException) {
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleConversionNotSupported((ConversionNotSupportedException)ex, headers, status, request);
    } else if(ex instanceof TypeMismatchException) {
        status = HttpStatus.BAD_REQUEST;
        return handleTypeMismatch((TypeMismatchException)ex, headers, status, request);
    } else if(ex instanceof HttpMessageNotReadableException) {
        status = HttpStatus.BAD_REQUEST;
        return handleHttpMessageNotReadable((HttpMessageNotReadableException)ex, headers, status, request);
    } else if(ex instanceof HttpMessageNotWritableException) {
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleHttpMessageNotWritable((HttpMessageNotWritableException)ex, headers, status, request);
    } else if(ex instanceof MethodArgumentNotValidException) {
        status = HttpStatus.BAD_REQUEST;
        return handleMethodArgumentNotValid((MethodArgumentNotValidException)ex, headers, status, request);
    } else if(ex instanceof MissingServletRequestPartException) {
        status = HttpStatus.BAD_REQUEST;
        return handleMissingServletRequestPart((MissingServletRequestPartException)ex, headers, status, request);
    } else if(ex instanceof BindException) {
        status = HttpStatus.BAD_REQUEST;
        return handleBindingResult(((BindException) ex).getBindingResult(), (BindException)ex, null, headers, status, request);
    } else if(ex instanceof NoHandlerFoundException) {
        status = HttpStatus.NOT_FOUND;
        return handleNoHandlerFoundException((NoHandlerFoundException)ex, headers, status, request);
    } else {
        logger.warn("Unknown exception type: " + ex.getClass().getName());
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleExceptionInternal(ex, (Object)null, headers, status, request);
    }
}
项目:easy-mybatis    文件:RestExceptionHandler.java   
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, HttpServletRequest request) {
    return handleExceptionInternal(ex, (Object) null, headers, status, request);
}
项目:konker-platform    文件:GlobalControllerExceptionHandler.java   
@ExceptionHandler(value = NoHandlerFoundException.class)
public ModelAndView handleNotFound(HttpServletRequest req, HttpServletResponse res, NoHandlerFoundException ex) {
    LOGGER.error("GlobalControllerExceptionHandler: ", ex);
    return new ModelAndView("error/index");
}
项目:backstopper    文件:OneOffSpringFrameworkExceptionHandlerListener.java   
@Override
public ApiExceptionHandlerListenerResult shouldHandleException(Throwable ex) {
    SortedApiErrorSet handledErrors = null;
    List<Pair<String, String>> extraDetailsForLogging = new ArrayList<>();

    if (ex instanceof NoHandlerFoundException) {
        handledErrors = singletonSortedSetOf(projectApiErrors.getNotFoundApiError());
    }

    if (ex instanceof TypeMismatchException) {
        TypeMismatchException tme = (TypeMismatchException) ex;
        Map<String, Object> metadata = new LinkedHashMap<>();

        utils.addBaseExceptionMessageToExtraDetailsForLogging(ex, extraDetailsForLogging);

        String badPropName = extractPropertyName(tme);
        String badPropValue = (tme.getValue() == null) ? null : String.valueOf(tme.getValue());
        String requiredTypeNoInfoLeak = extractRequiredTypeNoInfoLeak(tme);

        extraDetailsForLogging.add(Pair.of("bad_property_name", badPropName));
        if (badPropName != null) {
            metadata.put("bad_property_name", badPropName);
        }
        extraDetailsForLogging.add(Pair.of("bad_property_value", String.valueOf(tme.getValue())));
        if (badPropValue != null) {
            metadata.put("bad_property_value", badPropValue);
        }
        extraDetailsForLogging.add(Pair.of("required_type", String.valueOf(tme.getRequiredType())));
        if (requiredTypeNoInfoLeak != null) {
            metadata.put("required_type", requiredTypeNoInfoLeak);
        }
        handledErrors = singletonSortedSetOf(
            new ApiErrorWithMetadata(projectApiErrors.getTypeConversionApiError(), metadata)
        );
    }

    if (ex instanceof ServletRequestBindingException) {
        // Malformed requests can be difficult to track down - add the exception's message to our logging details
        utils.addBaseExceptionMessageToExtraDetailsForLogging(ex, extraDetailsForLogging);
        handledErrors = singletonSortedSetOf(projectApiErrors.getMalformedRequestApiError());
    }

    if (ex instanceof HttpMessageConversionException) {
        // Malformed requests can be difficult to track down - add the exception's message to our logging details
        utils.addBaseExceptionMessageToExtraDetailsForLogging(ex, extraDetailsForLogging);

        if (isMissingExpectedContentCase((HttpMessageConversionException) ex)) {
            handledErrors = singletonSortedSetOf(projectApiErrors.getMissingExpectedContentApiError());
        }
        else {
            // NOTE: If this was a HttpMessageNotReadableException with a cause of
            //          com.fasterxml.jackson.databind.exc.InvalidFormatException then we *could* theoretically map
            //          to projectApiErrors.getTypeConversionApiError(). If we ever decide to implement this, then
            //          InvalidFormatException does contain reference to the field that failed to convert - we can
            //          get to it via getPath(), iterating over each path object, and building the full path by
            //          concatenating them with '.'. For now we'll just turn all errors in this category into
            //          projectApiErrors.getMalformedRequestApiError().
            handledErrors = singletonSortedSetOf(projectApiErrors.getMalformedRequestApiError());
        }
    }

    if (ex instanceof HttpMediaTypeNotAcceptableException) {
        handledErrors = singletonSortedSetOf(projectApiErrors.getNoAcceptableRepresentationApiError());
    }

    if (ex instanceof HttpMediaTypeNotSupportedException) {
        handledErrors = singletonSortedSetOf(projectApiErrors.getUnsupportedMediaTypeApiError());
    }

    if (ex instanceof HttpRequestMethodNotSupportedException) {
        handledErrors = singletonSortedSetOf(projectApiErrors.getMethodNotAllowedApiError());
    }

    if (handledErrors != null) {
        return ApiExceptionHandlerListenerResult.handleResponse(handledErrors, extraDetailsForLogging);
    }

    return ApiExceptionHandlerListenerResult.ignoreResponse();
}
项目:SpringRestBoilerplate    文件:GlobalExceptionHander.java   
@ExceptionHandler(value = NoHandlerFoundException.class)
public ResponseEntity<String> handleException(NoHandlerFoundException ex) {
    String json = "{\"error\":\"Resource not found.\"}";
    return new ResponseEntity<String>(json, HttpStatus.NOT_FOUND);
}
项目:java-spring-jspx-hibernate-template    文件:ExceptionHandlingController.java   
@ExceptionHandler(NoHandlerFoundException.class)
public String handle404Error(NoHandlerFoundException e) {
    return Constants.Url.REDIRECT + Constants.Url.ROOT;
}
项目:easy-mybatis    文件:RestExceptionHandler.java   
@ExceptionHandler({NoSuchRequestHandlingMethodException.class,
        HttpRequestMethodNotSupportedException.class,
        HttpMediaTypeNotSupportedException.class,
        HttpMediaTypeNotAcceptableException.class,
        MissingServletRequestParameterException.class,
        ServletRequestBindingException.class,
        ConversionNotSupportedException.class,
        TypeMismatchException.class,
        HttpMessageNotReadableException.class,
        HttpMessageNotWritableException.class,
        MethodArgumentNotValidException.class,
        MissingServletRequestPartException.class,
        BindException.class,
        NoHandlerFoundException.class})
public final ResponseEntity<Object> handleException(Exception ex, HttpServletRequest request) {
    HttpHeaders headers = new HttpHeaders();
    HttpStatus status;
    if(ex instanceof NoSuchRequestHandlingMethodException) {
        status = HttpStatus.NOT_FOUND;
        return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException)ex, headers, status, request);
    } else if(ex instanceof HttpRequestMethodNotSupportedException) {
        status = HttpStatus.METHOD_NOT_ALLOWED;
        return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException)ex, headers, status, request);
    } else if(ex instanceof HttpMediaTypeNotSupportedException) {
        status = HttpStatus.UNSUPPORTED_MEDIA_TYPE;
        return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException)ex, headers, status, request);
    } else if(ex instanceof HttpMediaTypeNotAcceptableException) {
        status = HttpStatus.NOT_ACCEPTABLE;
        return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException)ex, headers, status, request);
    } else if(ex instanceof MissingServletRequestParameterException) {
        status = HttpStatus.BAD_REQUEST;
        return handleMissingServletRequestParameter((MissingServletRequestParameterException)ex, headers, status, request);
    } else if(ex instanceof ServletRequestBindingException) {
        status = HttpStatus.BAD_REQUEST;
        return handleServletRequestBindingException((ServletRequestBindingException)ex, headers, status, request);
    } else if(ex instanceof ConversionNotSupportedException) {
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleConversionNotSupported((ConversionNotSupportedException)ex, headers, status, request);
    } else if(ex instanceof TypeMismatchException) {
        status = HttpStatus.BAD_REQUEST;
        return handleTypeMismatch((TypeMismatchException)ex, headers, status, request);
    } else if(ex instanceof HttpMessageNotReadableException) {
        status = HttpStatus.BAD_REQUEST;
        return handleHttpMessageNotReadable((HttpMessageNotReadableException)ex, headers, status, request);
    } else if(ex instanceof HttpMessageNotWritableException) {
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleHttpMessageNotWritable((HttpMessageNotWritableException)ex, headers, status, request);
    } else if(ex instanceof MethodArgumentNotValidException) {
        status = HttpStatus.BAD_REQUEST;
        return handleMethodArgumentNotValid((MethodArgumentNotValidException)ex, headers, status, request);
    } else if(ex instanceof MissingServletRequestPartException) {
        status = HttpStatus.BAD_REQUEST;
        return handleMissingServletRequestPart((MissingServletRequestPartException)ex, headers, status, request);
    } else if(ex instanceof BindException) {
        status = HttpStatus.BAD_REQUEST;
        return handleBindingResult(((BindException) ex).getBindingResult(), (BindException)ex, null, headers, status, request);
    } else if(ex instanceof NoHandlerFoundException) {
        status = HttpStatus.NOT_FOUND;
        return handleNoHandlerFoundException((NoHandlerFoundException)ex, headers, status, request);
    } else {
        logger.warn("Unknown exception type: " + ex.getClass().getName());
        status = HttpStatus.INTERNAL_SERVER_ERROR;
        return handleExceptionInternal(ex, (Object)null, headers, status, request);
    }
}
项目:easy-mybatis    文件:RestExceptionHandler.java   
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, HttpServletRequest request) {
    return handleExceptionInternal(ex, (Object) null, headers, status, request);
}
项目:dawg    文件:AdminController.java   
@RequestMapping(value="/user/{userId}", method = { RequestMethod.GET } )
@ResponseBody
public DawgUserAndRoles getUser(@PathVariable String userId) throws UserException, NoHandlerFoundException {
    if (userService == null) throw new NoHandlerFoundException(RequestMethod.GET.name(), "/user/" + userId, null);
    return userService.getUser(userId);
}