Spring or Springboot Unified exception handling
76150370
One, this article describes the custom exception handling of spring MVC, where the client receives a hint of a more friendly JSON format when throwing out a defined exception in the controller. Rather than the usual error page.
Second, the scene description: Implement the public API, verify the logic of the API key, put in the interceptor to judge (equivalent to in the controller) and throw an exception, the user received a similar prompt:
The HTTP status code can also be controlled freely.
Three, Solution:
1, throw an exception in the Ratelimitinterceptor.java Interceptor:
[Java] View plain copy
- Public class Ratelimitinterceptor extends handlerinterceptoradapter{
- @Autowired private Redisservice rs;
- /**
- * Flow Control Check Entry
- */
- @Override
- Public Boolean prehandle (httpservletrequest request,
- HttpServletResponse response, Object handler) throws Requiredparameterexception, Signexception, ratelimitexception,exception {
- Super.prehandle (Request, response, handler);
- String AppKey = Request.getparameter ("AppKey");
- //Determine if the Appkey is empty or legal
- if (AppKey = = null) {
- throw New Requiredparameterexception ("");
- }Else if (appkeyutils.isformatcorrect (AppKey) | |!rs.isexist (appKey)) {
- throw new Signexception ();
- }Else {
- try {
- Appcall Appcall = appcall.create (AppKey, Appkeyutils.getplandetails (AppKey));
- Appcall.decrease ();
- Rs.save (Appcall);
- System.out.println ("Ratelimitinterceptor pass.");
- } catch (Ratelimitexception e) {
- //Throw overrun exception
- throw new Ratelimitexception ();
- }
- }
- return true;
- }
- }
Spring or Springboot Unified exception handling