org.springframework.web.servlet.NoHandlerFoundException Java Examples

The following examples show how to use org.springframework.web.servlet.NoHandlerFoundException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppSiteController.java    From alpha-wallet-android with MIT License 6 votes vote down vote up
@GetMapping(value = "/{UniversalLink}")
public @ResponseBody String handleUniversalLink(
        @PathVariable("UniversalLink") String universalLink,
        Model model,
        HttpServletRequest request
)
        throws IOException, SAXException, NoHandlerFoundException
{
    String domain = request.getServerName();
    ParseMagicLink parser = new ParseMagicLink(cryptoFunctions, null);
    MagicLinkData data;
    model.addAttribute("base64", universalLink);

    try
    {
        data = parser.parseUniversalLink(universalLink);
        data.chainId = MagicLinkInfo.getNetworkIdFromDomain(domain);
        model.addAttribute("domain", MagicLinkInfo.getMagicLinkDomainFromNetworkId(data.chainId));
    }
    catch (SalesOrderMalformed e)
    {
        return "error: " + e;
    }
    parser.getOwnerKey(data);
    return handleTokenLink(data, universalLink);
}
 
Example #2
Source File: RestExceptionHandler.java    From java-starthere with MIT License 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex,
                                                               HttpHeaders headers,
                                                               HttpStatus status,
                                                               WebRequest request)
{
    ErrorDetail errorDetail = new ErrorDetail();
    errorDetail.setTimestamp(new Date().getTime());
    errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
    errorDetail.setTitle(ex.getRequestURL());
    errorDetail.setDetail(request.getDescription(true));
    errorDetail.setDeveloperMessage("Rest Handler Not Found (check for valid URI)");

    return new ResponseEntity<>(errorDetail,
                                headers,
                                HttpStatus.NOT_FOUND);
}
 
Example #3
Source File: ControllerExceptionHandler.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.BAD_GATEWAY)
public BaseResponse handleNoHandlerFoundException(NoHandlerFoundException e) {
    BaseResponse<?> baseResponse = handleBaseException(e);
    HttpStatus status = HttpStatus.BAD_GATEWAY;
    baseResponse.setStatus(status.value());
    baseResponse.setMessage(status.getReasonPhrase());
    return baseResponse;
}
 
Example #4
Source File: ResponseEntityExceptionHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #5
Source File: DefaultHandlerExceptionResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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());
}
 
Example #6
Source File: GlobalExceptionHandler.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 404 - Not Found
 */
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public String noHandlerFoundException(NoHandlerFoundException e, Model model) {
    log.error("Not Found", e);
    String message = "【页面不存在】" + e.getMessage();
    model.addAttribute("message", message);
    model.addAttribute("code", 404);
    return viewName;
}
 
Example #7
Source File: GlobalExceptionTranslator.java    From staffjoy with MIT License 5 votes vote down vote up
@ExceptionHandler(NoHandlerFoundException.class)
public BaseResponse handleError(NoHandlerFoundException e) {
    logger.error("404 Not Found", e);
    return BaseResponse
            .builder()
            .code(ResultCode.NOT_FOUND)
            .message(e.getMessage())
            .build();
}
 
Example #8
Source File: ResponseEntityExceptionHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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);
}
 
Example #9
Source File: GlobalDefaultExceptionHandler.java    From unified-dispose-springboot with Apache License 2.0 5 votes vote down vote up
/**
 * NoHandlerFoundException 404 异常处理
 */
@ExceptionHandler(value = NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Result handlerNoHandlerFoundException(NoHandlerFoundException e) throws Throwable {
    errorDispose(e);
    outPutErrorWarn(NoHandlerFoundException.class, CommonErrorCode.NOT_FOUND, e);
    return Result.ofFail(CommonErrorCode.NOT_FOUND);
}
 
Example #10
Source File: ExceptionResolver.java    From spring-boot-vue-admin with Apache License 2.0 5 votes vote down vote up
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public Result apiNotFoundException(final Throwable e, final HttpServletRequest request) {
  log.error("==> API不存在: {}", e.getMessage());
  e.printStackTrace();
  return ResultGenerator.genFailedResult(
      "API [" + UrlUtils.getMappingUrl(request) + "] not existed");
}
 
Example #11
Source File: ServletWebErrorHandler.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * Only handles {@link ServletException}s and {@link HttpMessageNotReadableException}s.
 *
 * @param exception The exception to examine.
 * @return {@code true} when can handle the {@code exception}, {@code false} otherwise.
 */
@Override
public boolean canHandle(Throwable exception) {
    return exception instanceof HttpMediaTypeNotAcceptableException ||
        exception instanceof HttpMediaTypeNotSupportedException ||
        exception instanceof HttpRequestMethodNotSupportedException ||
        exception instanceof MissingServletRequestParameterException ||
        exception instanceof MissingServletRequestPartException ||
        exception instanceof NoHandlerFoundException ||
        exception instanceof HttpMessageNotReadableException;
}
 
Example #12
Source File: ServletWebErrorHandlerTest.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private Object[] provideParamsForCanHandle() {
    return p(
        p(null, false),
        p(new RuntimeException(), false),
        p(new NoHandlerFoundException(null, null, null), true),
        p(new HttpMessageNotReadableException("", mock(HttpInputMessage.class)), true),
        p(new MissingServletRequestParameterException("name", "String"), true),
        p(new HttpMediaTypeNotAcceptableException(""), true),
        p(new HttpMediaTypeNotSupportedException(""), true),
        p(new HttpRequestMethodNotSupportedException(""), true),
        p(new MissingServletRequestPartException("file"), true)
    );
}
 
Example #13
Source File: WebExceptionHandler.java    From Shiro-Action with MIT License 5 votes vote down vote up
@ExceptionHandler
public String unauthorized(NoHandlerFoundException e) {
    if (log.isDebugEnabled()) {
        log.debug("请求的地址不存在", e);
    }
    return generateErrorInfo(ResultBean.FAIL, "请求的地址不存在", HttpStatus.NOT_FOUND.value());
}
 
Example #14
Source File: GlobalExceptionHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResponse handlerException(Exception e) {
    if (e instanceof NoHandlerFoundException) {
        log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod());
        return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND);
    } else if (e instanceof HttpRequestMethodNotSupportedException) {
        log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
        return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD);
    } else if (e instanceof MethodArgumentNotValidException) {
        log.error("【全局异常拦截】MethodArgumentNotValidException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult()
                .getAllErrors()
                .get(0)
                .getDefaultMessage(), null);
    } else if (e instanceof ConstraintViolationException) {
        log.error("【全局异常拦截】ConstraintViolationException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations())
                .getMessage(), null);
    } else if (e instanceof MethodArgumentTypeMismatchException) {
        log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH);
    } else if (e instanceof HttpMessageNotReadableException) {
        log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_NULL);
    } else if (e instanceof BadCredentialsException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR);
    } else if (e instanceof DisabledException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USER_DISABLED);
    } else if (e instanceof BaseException) {
        log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage());
        return ApiResponse.ofException((BaseException) e);
    }

    log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
    return ApiResponse.ofStatus(Status.ERROR);
}
 
Example #15
Source File: ServerExceptionHandler.java    From oauth2-server with MIT License 5 votes vote down vote up
@ExceptionHandler({
    NoHandlerFoundException.class
})
public ResponseEntity<Object> handleNoHandlerFoundException(Exception ex, HttpServletRequest request) {
    HttpStatus httpStatus = HttpStatus.NOT_FOUND;
    logRequest(ex, httpStatus, request);
    HttpHeaders headers = new HttpHeaders();
    Map<String, Object> responseResult = new HashMap<>(16);
    responseResult.put("status", httpStatus.value());
    responseResult.put("message", ex.getMessage());
    responseResult.put("url", request.getRequestURL());
    return new ResponseEntity<>(responseResult, headers, httpStatus);
}
 
Example #16
Source File: AppSiteController.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private TokenDefinition getTokenDefinition(int chainId, String contractAddress) throws IOException, SAXException, NoHandlerFoundException
{
    File xml = null;
    TokenDefinition definition = null;
    if (addresses.containsKey(chainId) && addresses.get(chainId).containsKey(contractAddress))
    {
        xml = addresses.get(chainId).get(contractAddress);
        if (xml == null) {
            /* this is impossible to happen, because at least 1 xml should present or main() bails out */
            throw new NoHandlerFoundException("GET", "/" + contractAddress, new HttpHeaders());
        }
        try(FileInputStream in = new FileInputStream(xml)) {
            // TODO: give more detail in the error
            // TODO: reflect on this: should the page bail out for contracts with completely no matching XML?
            definition = new TokenDefinition(in, new Locale("en"), null);
        }
    }
    return definition;
}
 
Example #17
Source File: GlobalExceptionHandler.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
/**
 * 404 - Not Found
 */
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public String noHandlerFoundException(NoHandlerFoundException e, Model model) {
    logger.error("Not Found", e);
    String message = "【页面不存在】" + e.getMessage();
    model.addAttribute("message", message);
    model.addAttribute("code", 404);
    System.out.println("404404错误");
    return viewName;
}
 
Example #18
Source File: ServerExceptionHandler.java    From oauth2-resource with MIT License 5 votes vote down vote up
@ExceptionHandler({
    NoHandlerFoundException.class
})
public ResponseEntity<Object> handleNoHandlerFoundException(Exception ex, HttpServletRequest request) {
    HttpStatus httpStatus = HttpStatus.NOT_FOUND;
    logRequest(ex, httpStatus, request);
    HttpHeaders headers = new HttpHeaders();
    Map<String, Object> responseResult = new HashMap<>(16);
    responseResult.put("status", httpStatus.value());
    responseResult.put("message", ex.getMessage());
    responseResult.put("url", request.getRequestURL());
    return new ResponseEntity<>(responseResult, headers, httpStatus);
}
 
Example #19
Source File: RestExceptionHandler.java    From spring-glee-o-meter with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(
        NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    ApiError apiError = new ApiError(BAD_REQUEST);
    apiError.setMessage(String.format("Could not find the %s method for URL %s", ex.getHttpMethod(), ex.getRequestURL()));
    apiError.setDebugMessage(ex.getMessage());
    return buildResponseEntity(apiError);
}
 
Example #20
Source File: ExceptionHandler.java    From mini-platform with MIT License 5 votes vote down vote up
@ResponseBody
@org.springframework.web.bind.annotation.ExceptionHandler(value = NoHandlerFoundException.class)
public ExceptionResult noHandlerFoundException(HttpServletRequest request, NoHandlerFoundException e) {
    String uri = getUri(request);
    String stackTrace = getStackTrace(e.getStackTrace());
    Integer code = HttpStatus.NOT_FOUND.value();

    writeLog(uri, "接口不存在!", stackTrace);
    return new ExceptionResult(code, "接口不存在!", code, stackTrace, uri);
}
 
Example #21
Source File: GlobalExceptionHandler.java    From ywh-frame with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 404错误拦截   已测试
 * @param ex 异常信息
 * @return 返回前端异常信息
 */
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Result noHandlerNotFound(NoHandlerFoundException ex){
    log.error("错误详情:" + ex.getMessage(),ex);
    return Result.errorJson(BaseEnum.NO_HANDLER.getMsg(),BaseEnum.NO_HANDLER.getIndex());
}
 
Example #22
Source File: GlobalExceptionHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResponse handlerException(Exception e) {
    if (e instanceof NoHandlerFoundException) {
        log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod());
        return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND);
    } else if (e instanceof HttpRequestMethodNotSupportedException) {
        log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
        return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD);
    } else if (e instanceof MethodArgumentNotValidException) {
        log.error("【全局异常拦截】MethodArgumentNotValidException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult()
                .getAllErrors()
                .get(0)
                .getDefaultMessage(), null);
    } else if (e instanceof ConstraintViolationException) {
        log.error("【全局异常拦截】ConstraintViolationException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations())
                .getMessage(), null);
    } else if (e instanceof MethodArgumentTypeMismatchException) {
        log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH);
    } else if (e instanceof HttpMessageNotReadableException) {
        log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_NULL);
    } else if (e instanceof BadCredentialsException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR);
    } else if (e instanceof DisabledException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USER_DISABLED);
    } else if (e instanceof BaseException) {
        log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage());
        return ApiResponse.ofException((BaseException) e);
    }

    log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
    return ApiResponse.ofStatus(Status.ERROR);
}
 
Example #23
Source File: CustomRestExceptionHandler.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #24
Source File: DefaultHandlerExceptionResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #25
Source File: ResponseEntityExceptionHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #26
Source File: OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleException_should_return_not_found_error_when_passed_NoHandlerFoundException() {
    // given
    NoHandlerFoundException ex = new NoHandlerFoundException();

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

    // then
    validateResponse(result, true, singletonList(testProjectApiErrors.getNotFoundApiError()));
}
 
Example #27
Source File: NoHandlerFoundAdviceTrait.java    From problem-spring-web with MIT License 5 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default ResponseEntity<Problem> handleNoHandlerFound(
        final NoHandlerFoundException exception,
        final NativeWebRequest request) {
    return create(Status.NOT_FOUND, exception, request);
}
 
Example #28
Source File: AdviceTraitLoggingTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Test
void shouldLogOnCreate() {
    Throwable throwable = new NoHandlerFoundException("GET", "/", new HttpHeaders());
    NativeWebRequest request = mock(NativeWebRequest.class);
    ArgumentCaptor<Problem> problemCaptor = ArgumentCaptor.forClass(Problem.class);

    unit.create(Status.BAD_REQUEST, throwable, request);

    verify(unit).log(eq(throwable), problemCaptor.capture(), eq(request), eq(HttpStatus.BAD_REQUEST));
    assertThat(problemCaptor.getValue().getStatus(), is(Status.BAD_REQUEST));
}
 
Example #29
Source File: NotFoundHandler.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<String> renderDefaultPage() {
    try {
        String body = StreamUtils.copyToString(new ClassPathResource("/public/index.html").getInputStream(), Charset
            .defaultCharset());
        return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(body);
    } catch (final IOException e) {
        LoggerFactory.getLogger(NotFoundHandler.class).error("err", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                             .body("There was an error completing the action.");
    }
}
 
Example #30
Source File: CustomRestExceptionHandler.java    From tutorials with MIT License 5 votes vote down vote up
@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());
}