下面列出了javax.validation.UnexpectedTypeException#org.springframework.web.HttpRequestMethodNotSupportedException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @param
* @return
* @author GS
* @description 错误请求方式异常 HttpRequestMethodNotSupportedException
* @date 2018/2/28 17:32
*/
@ResponseBody
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public MessageResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
ex.printStackTrace();
log.info(">>>错误请求方式异常>>",ex);
String methods = "";
//支持的请求方式
String[] supportedMethods = ex.getSupportedMethods();
for (String method : supportedMethods) {
methods += method;
}
MessageResult result = MessageResult.error("Request method " + ex.getMethod() + " not supported !" +
" supported method : " + methods + "!");
return result;
}
@Override
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException 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.getMethod());
errorDetail.setDetail(request.getDescription(true));
errorDetail.setDeveloperMessage("HTTP Method Not Valid for Endpoint (check for valid URI and proper HTTP Method)");
return new ResponseEntity<>(errorDetail,
headers,
HttpStatus.NOT_FOUND);
}
/**
* @Author 政辉
* @param e
* @return
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result<?> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
StringBuffer sb = new StringBuffer();
sb.append("不支持");
sb.append(e.getMethod());
sb.append("请求方法,");
sb.append("支持以下");
String [] methods = e.getSupportedMethods();
if(methods!=null){
for(String str:methods){
sb.append(str);
sb.append("、");
}
}
log.error(sb.toString(), e);
//return Result.error("没有权限,请联系管理员授权");
return Result.error(405,sb.toString());
}
/**
* @param
* @return
* @author GS
* @description 错误请求方式异常 HttpRequestMethodNotSupportedException
* @date 2018/2/28 17:32
*/
@ResponseBody
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public MessageResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
ex.printStackTrace();
log.info(">>>错误请求方式异常>>",ex);
String methods = "";
//支持的请求方式
String[] supportedMethods = ex.getSupportedMethods();
for (String method : supportedMethods) {
methods += method;
}
MessageResult result = MessageResult.error("Request method " + ex.getMethod() + " not supported !" +
" supported method : " + methods + "!");
return result;
}
@Override
public void process(PluginContext ctx, PluginRestMsg msg) {
try {
log.debug("[{}] Processing REST msg: {}", ctx.getPluginId(), msg);
HttpMethod method = msg.getRequest().getMethod();
switch (method) {
case GET:
handleHttpGetRequest(ctx, msg);
break;
case POST:
handleHttpPostRequest(ctx, msg);
break;
case DELETE:
handleHttpDeleteRequest(ctx, msg);
break;
default:
msg.getResponseHolder().setErrorResult(new HttpRequestMethodNotSupportedException(method.name()));
}
log.debug("[{}] Processed REST msg.", ctx.getPluginId());
} catch (Exception e) {
log.warn("[{}] Exception during REST msg processing: {}", ctx.getPluginId(), e.getMessage(), e);
msg.getResponseHolder().setErrorResult(e);
}
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LocaleContextHolder.setLocale(request.getLocale());
try {
this.target.handleRequest(request, response);
}
catch (HttpRequestMethodNotSupportedException ex) {
String[] supportedMethods = ex.getSupportedMethods();
if (supportedMethods != null) {
response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
}
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
}
finally {
LocaleContextHolder.resetLocaleContext();
}
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Assert.state(this.target != null, "No HttpRequestHandler available");
LocaleContextHolder.setLocale(request.getLocale());
try {
this.target.handleRequest(request, response);
}
catch (HttpRequestMethodNotSupportedException ex) {
String[] supportedMethods = ex.getSupportedMethods();
if (supportedMethods != null) {
response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
}
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
}
finally {
LocaleContextHolder.resetLocaleContext();
}
}
/**
* Processes the incoming Hessian request and creates a Hessian response.
*/
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (!"POST".equals(request.getMethod())) {
throw new HttpRequestMethodNotSupportedException(request.getMethod(),
new String[] {"POST"}, "HessianServiceExporter only supports POST requests");
}
response.setContentType(CONTENT_TYPE_HESSIAN);
try {
invoke(request.getInputStream(), response.getOutputStream());
}
catch (Throwable ex) {
throw new NestedServletException("Hessian skeleton invocation failed", ex);
}
}
@ResponseBody
@RequestMapping(value = ENTITY_LOCK_MAPPING, method = RequestMethod.DELETE)
public ResponseEntity<Resource<?>> unlock(RootResourceInformation repoInfo,
@PathVariable String repository,
@PathVariable String id, Principal principal)
throws ResourceNotFoundException, HttpRequestMethodNotSupportedException {
Object domainObj = repoInfo.getInvoker().invokeFindById(id).get();
domainObj = ReflectionUtils.invokeMethod(UNLOCK_METHOD, repositories.getRepositoryFor(domainObj.getClass()).get(), domainObj);
if (domainObj != null) {
return ResponseEntity.ok().build();
} else {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
}
}
/**
* Processes the incoming Hessian request and creates a Hessian response.
*/
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (!"POST".equals(request.getMethod())) {
throw new HttpRequestMethodNotSupportedException(request.getMethod(),
new String[] {"POST"}, "HessianServiceExporter only supports POST requests");
}
response.setContentType(CONTENT_TYPE_HESSIAN);
try {
invoke(request.getInputStream(), response.getOutputStream());
}
catch (Throwable ex) {
throw new NestedServletException("Hessian skeleton invocation failed", ex);
}
}
/**
* Validate the given type-level mapping metadata against the current request,
* checking HTTP request method and parameter conditions.
* @param mapping the mapping metadata to validate
* @param request current HTTP request
* @throws Exception if validation failed
*/
protected void validateMapping(RequestMapping mapping, HttpServletRequest request) throws Exception {
RequestMethod[] mappedMethods = mapping.method();
if (!ServletAnnotationMappingUtils.checkRequestMethod(mappedMethods, request)) {
String[] supportedMethods = new String[mappedMethods.length];
for (int i = 0; i < mappedMethods.length; i++) {
supportedMethods[i] = mappedMethods[i].name();
}
throw new HttpRequestMethodNotSupportedException(request.getMethod(), supportedMethods);
}
String[] mappedParams = mapping.params();
if (!ServletAnnotationMappingUtils.checkParameters(mappedParams, request)) {
throw new UnsatisfiedServletRequestParameterException(mappedParams, request.getParameterMap());
}
String[] mappedHeaders = mapping.headers();
if (!ServletAnnotationMappingUtils.checkHeaders(mappedHeaders, request)) {
throw new ServletRequestBindingException("Header conditions \"" +
StringUtils.arrayToDelimitedString(mappedHeaders, ", ") +
"\" not met for actual request");
}
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Map<String, Object> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
logger.error("不支持当前请求方法", e);
Map<String, Object> map = new HashMap<String, Object>();
map.put("rspCode", 405);
map.put("rspMsg", e.getMessage());
//发生异常进行日志记录,写入数据库或者其他处理,此处省略
return map;
}
/**
* 请求方式不支持
*/
@ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
public AjaxResult handleException(HttpRequestMethodNotSupportedException e)
{
log.error(e.getMessage(), e);
return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
}
/**
* 添加全局异常处理流程
*
* @param e
* @return
* @throws Exception
*/
@ResponseBody
@ExceptionHandler(Exception.class)
public ResponseDTO exceptionHandler(Exception e) {
log.error("error:", e);
// http 请求方式错误
if (e instanceof HttpRequestMethodNotSupportedException) {
return ResponseDTO.wrap(ResponseCodeConst.REQUEST_METHOD_ERROR);
}
// 参数类型错误
if (e instanceof TypeMismatchException) {
return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM);
}
// json 格式错误
if (e instanceof HttpMessageNotReadableException) {
return ResponseDTO.wrap(ResponseCodeConst.JSON_FORMAT_ERROR);
}
// 参数校验未通过
if (e instanceof MethodArgumentNotValidException) {
List<FieldError> fieldErrors = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors();
List<String> msgList = fieldErrors.stream().map(FieldError :: getDefaultMessage).collect(Collectors.toList());
return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM, String.join(",", msgList));
}
if (e instanceof SmartBusinessException) {
return ResponseDTO.wrap(ResponseCodeConst.SYSTEM_ERROR);
}
return ResponseDTO.wrap(ResponseCodeConst.SYSTEM_ERROR);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@StoreType("contentstore")
@RequestMapping(value = ENTITY_SEARCHMETHOD_MAPPING, method = RequestMethod.GET)
public ResponseEntity<?> searchContent(RootResourceInformation repoInfo,
DefaultedPageable pageable,
Sort sort,
PersistentEntityResourceAssembler assembler,
@PathVariable String repository,
@RequestParam(name = "keyword") List<String> keywords)
throws HttpRequestMethodNotSupportedException {
return searchContentInternal(repoInfo, pageable, sort, assembler, "findKeyword", keywords.toArray(new String[]{}));
}
public static Iterable findAll(Repositories repositories, String repository)
throws HttpRequestMethodNotSupportedException {
Iterable entities = null;
RepositoryInformation ri = RepositoryUtils.findRepositoryInformation(repositories, repository);
if (ri == null) {
throw new ResourceNotFoundException();
}
Class<?> domainObjClazz = ri.getDomainType();
Class<?> idClazz = ri.getIdType();
Optional<Method> findAllMethod = ri.getCrudMethods().getFindAllMethod();
if (!findAllMethod.isPresent()) {
throw new HttpRequestMethodNotSupportedException("fineAll");
}
entities = (Iterable) ReflectionUtils.invokeMethod(findAllMethod.get(),
repositories.getRepositoryFor(domainObjClazz));
if (null == entities) {
throw new ResourceNotFoundException();
}
return entities;
}
/**
* Customize the response for HttpRequestMethodNotSupportedException.
* <p>This method logs a warning, sets the "Allow" header, 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> handleHttpRequestMethodNotSupported(
HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
pageNotFoundLogger.warn(ex.getMessage());
Set<HttpMethod> supportedMethods = ex.getSupportedHttpMethods();
if (!CollectionUtils.isEmpty(supportedMethods)) {
headers.setAllow(supportedMethods);
}
return handleExceptionInternal(ex, null, headers, status, request);
}
@Test
public void handleHttpRequestMethodNotSupported() {
HttpRequestMethodNotSupportedException ex =
new HttpRequestMethodNotSupportedException("GET", new String[]{"POST", "PUT"});
ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
assertNotNull("No ModelAndView returned", mav);
assertTrue("No Empty ModelAndView returned", mav.isEmpty());
assertEquals("Invalid status code", 405, response.getStatus());
assertEquals("Invalid Allow header", "POST, PUT", response.getHeader("Allow"));
}
@Test
public void httpRequestMethodNotSupported() {
List<String> supported = Arrays.asList("POST", "DELETE");
Exception ex = new HttpRequestMethodNotSupportedException("GET", supported);
ResponseEntity<Object> responseEntity = testException(ex);
assertEquals(EnumSet.of(HttpMethod.POST, HttpMethod.DELETE), responseEntity.getHeaders().getAllow());
}
@Test
public void getHandlerRequestMethodNotAllowed() throws Exception {
try {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar");
this.handlerMapping.getHandler(request);
fail("HttpRequestMethodNotSupportedException expected");
}
catch (HttpRequestMethodNotSupportedException ex) {
assertArrayEquals("Invalid supported methods", new String[]{"GET", "HEAD"},
ex.getSupportedMethods());
}
}
@StoreType("contentstore")
@RequestMapping(value = BASE_MAPPING, method = RequestMethod.PUT)
@ResponseBody
public void setContent(HttpServletRequest request,
@RequestHeader HttpHeaders headers,
@PathVariable String repository,
@PathVariable String id,
@PathVariable String contentProperty,
@PathVariable String contentId)
throws IOException, HttpRequestMethodNotSupportedException {
this.replaceContentInternal(headers, repositories, storeService, repository, id,
contentProperty, contentId, request.getHeader("Content-Type"), null,
request.getInputStream());
}
/**
* 请求方式不支持异常
* 比如:POST方式的API, GET方式请求
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
ResponseMessage handleException(HttpRequestMethodNotSupportedException exception) {
return ResponseMessage
.error(HttpStatus.METHOD_NOT_ALLOWED.value(), "不支持的请求方式")
.result(exception.getSupportedHttpMethods());
}
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public FebsResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
String message = "该方法不支持" + StringUtils.substringBetween(e.getMessage(), "'", "'") + "请求方法";
log.error(message);
return new FebsResponse().message(message);
}
@Test
public void processMethodNotSupportedExceptionTest() throws Exception {
MvcResult res = mock.perform(post("/api/account")
.content("{\"testFakeParam\"}"))
.andExpect(status().isMethodNotAllowed())
.andReturn();
assertThat(res.getResolvedException(), instanceOf(HttpRequestMethodNotSupportedException.class));
}
@Test
void noAllowIfNoneAllowed() {
final MethodNotAllowedAdviceTrait unit = new MethodNotAllowedAdviceTrait() {
};
final ResponseEntity<Problem> entity = unit.handleRequestMethodNotSupportedException(
new HttpRequestMethodNotSupportedException("non allowed", new String[]{}), mock(NativeWebRequest.class));
assertThat(entity.getHeaders(), not(hasKey("Allow")));
}
/**
* 请求方式不支持
*/
@ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
public AjaxResult handleException(HttpRequestMethodNotSupportedException e)
{
log.error(e.getMessage(), e);
return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
}
/**
* 处理HttpRequestMethodNotSupportedException异常的方法.
* @param request - HttpRequest对象
* @param response - HttpResponse对象
* @return 返回一个包含异常信息的ModelAndView对象
*/
@ResponseStatus(value=HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ModelAndView methodNotAllowedView(
HttpServletRequest request, HttpServletResponse response) {
ModelAndView view = new ModelAndView("errors/404");
return view;
}
@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);
}
@StoreType("contentstore")
@RequestMapping(value = BASE_MAPPING, method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<?> deleteContent(@RequestHeader HttpHeaders headers,
@PathVariable String repository,
@PathVariable String id,
@PathVariable String contentProperty,
@PathVariable String contentId)
throws HttpRequestMethodNotSupportedException {
Object domainObj = findOne(repositories, repository, id);
String etag = (BeanUtils.getFieldWithAnnotation(domainObj, Version.class) != null ? BeanUtils.getFieldWithAnnotation(domainObj, Version.class).toString() : null);
Object lastModifiedDate = (BeanUtils.getFieldWithAnnotation(domainObj, LastModifiedDate.class) != null ? BeanUtils.getFieldWithAnnotation(domainObj, LastModifiedDate.class) : null);
HeaderUtils.evaluateHeaderConditions(headers, etag, lastModifiedDate);
PersistentProperty<?> property = this.getContentPropertyDefinition(
repositories.getPersistentEntity(domainObj.getClass()), contentProperty);
Object contentPropertyValue = getContentProperty(domainObj, property, contentId);
Class<?> contentEntityClass = ContentPropertyUtils.getContentPropertyType(property);
ContentStoreInfo info = ContentStoreUtils.findContentStore(storeService, contentEntityClass);
info.getImpementation().unsetContent(contentPropertyValue);
// remove the content property reference from the data object
// setContentProperty(domainObj, property, contentId, null);
save(repositories, domainObj);
return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
}
@ExceptionHandler
public String test3(HttpRequestMethodNotSupportedException e,Model model){
ModelAndView modelAndView = new ModelAndView("/index");
Print.Normal("URL访问类型不正确:"+ e.getMessage());
//e.printStackTrace();
modelAndView.addObject("error","URL访问类型不正确。");
model.addAttribute("error","URL访问类型不正确。");
//返回错误信息,并显示给用户
//return e.getMessage();
return "exception";
}