下面列出了怎么用org.springframework.web.servlet.NoHandlerFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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);
}
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;
}
/**
* 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;
}
/**
* 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;
}
@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();
}
/**
* 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;
}
@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());
}
@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);
}
/**
*
* @param ex
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
public Response defaultErrorHandler(Exception ex) {
log.error("", ex);
Response response = new Response();
response.setMsg(ex.getMessage());
if (ex instanceof NoHandlerFoundException) {
response.setCode("404");
} else {
response.setCode("500");
}
response.setFlag("F");
return response;
}
@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);
}
@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());
}
@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);
}
/**
* 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);
}
@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");
}
/**
* 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;
}
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)
);
}
@ExceptionHandler
public String unauthorized(NoHandlerFoundException e) {
if (log.isDebugEnabled()) {
log.debug("请求的地址不存在", e);
}
return generateErrorInfo(ResultBean.FAIL, "请求的地址不存在", HttpStatus.NOT_FOUND.value());
}
@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);
}
@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);
}
@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;
}
@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);
}
@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);
}
@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);
}
/**
* 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());
}
@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);
}
@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());
}
@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());
}
@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);
}
@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()));
}