Home > Software design >  How to disable and throw exception for multiple endpoint in different Controller in Spring with anno
How to disable and throw exception for multiple endpoint in different Controller in Spring with anno

Time:08-27

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. I dont want to write if and else conditions to throw the Exceptions for 503 in each disabled endpoint.

Thanks

CodePudding user response:

You can do it, of course, but why? make a package on your project name like Exception.
after it, make the java class named it what is you need an exception.
example : 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

public static void checkNegative(int n) {
try {
    int[] a = new int[n];
} catch (NegativeArraySizeException e) {
    throw new IllegalArgumentException();
}

}

CodePudding user response:

you can custom a annotation(examples CheckEndpointsAnnotion), write on these controlers. write a Interceptor extends HandlerInterceptorAdapter ,overwrite this method

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);

  • Related