[英]How to disable and throw exception for multiple endpoint in different Controller in Spring with annotation
I have a code like:-我有一个像这样的代码: -
public interface OrderControler {
@RequestMapping(value = "/trackinginfo",
produces = "application/json",
method = RequestMethod.GET)
// Disabling with annotation
default ResponseEntity<String> getTrackingInfo() {...}
default ResponseEntity<String> getTrackingInfo() {...}
}
}
public interface OrderControler {
// Disabling with annotation
@RequestMapping(value = "/orderDetails",
produces = "application/json",
method = RequestMethod.GET)
default ResponseEntity<String> getorderDetails()
}
@RequestMapping(value = "/orderMethods",
produces = "application/json",
method = RequestMethod.GET)
default ResponseEntity<String> getorderMethod() {...}
}
}
I want to implementate an annotation which throws 503 error for some of the endpoints in the different controller.我想实现一个注释,它会为不同 controller 中的某些端点引发 503 错误。 I dont want to write if and else conditions to throw the Exceptions for 503 in each disabled endpoint.
我不想编写 if 和 else 条件来在每个禁用的端点中抛出 503 的异常。
Thanks谢谢
You can do it, of course, but why?当然,你可以做到,但为什么呢? make a package on your project name like Exception.
在您的项目名称上创建一个 package,例如 Exception。
after it, make the java class named it what is you need an exception.在它之后,将 java class 命名为你需要什么例外。
example: notFoundException示例:notFoundException
package com.class3.poinofsaleclass3.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.FOUND)
public class NotFoundException extends RuntimeException{
public NotFoundException (String message){
super(message);
}}
after it you can throw new NotFoundException
your coding place在它之后你可以在你的编码位置抛出新的
NotFoundException
public static void checkNegative(int n) {
try {
int[] a = new int[n];
} catch (NegativeArraySizeException e) {
throw new IllegalArgumentException();
}
} }
you can custom a annotation(examples CheckEndpointsAnnotion), write on these controlers.您可以自定义注释(例如 CheckEndpointsAnnotion),在这些控制器上编写。 write a Interceptor extends HandlerInterceptorAdapter,overwrite this method
写一个Interceptor extends HandlerInterceptorAdapter,覆盖这个方法
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
you can get the annotion or not by您可以通过以下方式获取或不获取注释
HandlerMethod handlerMethod = (HandlerMethod) handler;
CheckEndpointsAnnotion checkAnnotation = handlerMethod.getMethodAnnotation(CheckEndpointsAnnotion.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.