Spring or Springboot Unified exception handling

Source: Internet
Author: User

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
  1. Public class Ratelimitinterceptor extends handlerinterceptoradapter{
  2. @Autowired private Redisservice rs;
  3. /** 
  4. * Flow Control Check Entry
  5. */
  6. @Override
  7. Public Boolean prehandle (httpservletrequest request,
  8. HttpServletResponse response, Object handler) throws Requiredparameterexception, Signexception, ratelimitexception,exception {
  9. Super.prehandle (Request, response, handler);
  10. String AppKey = Request.getparameter ("AppKey");
  11. //Determine if the Appkey is empty or legal
  12. if (AppKey = = null) {
  13. throw New Requiredparameterexception ("");
  14. }Else if (appkeyutils.isformatcorrect (AppKey) | |!rs.isexist (appKey)) {
  15. throw new Signexception ();
  16. }Else {
  17. try {
  18. Appcall Appcall = appcall.create (AppKey, Appkeyutils.getplandetails (AppKey));
  19. Appcall.decrease ();
  20. Rs.save (Appcall);
  21. System.out.println ("Ratelimitinterceptor pass.");
  22. } catch (Ratelimitexception e) {
  23. //Throw overrun exception
  24. throw new Ratelimitexception ();
  25. }
  26. }
  27. return true;
  28. }
  29. }

Spring or Springboot Unified exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.