logo
down
shadow

Better way to handle exception is spring-boot


Better way to handle exception is spring-boot

By : joelong246
Date : November 20 2020, 07:00 PM
this one helps. You can use @RestControllerAdvice. Make a custom exception class CustomRedisException throw CustomRedisException Exception from every controller and handle this in separate class annotated with @RestControllerAdvice.
code :
@Override 
public boolean delMyStatus(String key) {
    try{
        return  redisTemplate.delete(key);
    }
    catch (Exception e){
        if(e.getCause() != null && e.getCause().getCause() instanceof RedisException) {      RedisException ex = (RedisException)e.getCause().getCause();
           throw new CustomRedisException(ex);
        } else {
            throw new IllegalStateException("...");
        }
    }
    return false;
}
@RestControllerAdvice(basePackages = "your base package here", basePackageClasses = RepositoryRestExceptionHandler.class)
public class GlobalRestExceptionHandler {

    @ExceptionHandler
    public ResponseEntity<ErrorResponse> handleCustomException(final CustomRedisExceptionex) {

        // code for exception handling here.

        return new ResponseEntity<>(
                new ErrorResponse(HttpStatus.PRECONDITION_FAILED.value(), ex.getMessage()),
                HttpStatus.PRECONDITION_FAILED);
    }
}


Share : facebook icon twitter icon
Custom exception handle with spring boot

Custom exception handle with spring boot


By : user3638024
Date : March 29 2020, 07:55 AM
Any of those help You can come up with a class like this to capture information to be sent in response in case of exception:-
code :
public class APIResponse  {
     int errorCode;
     String description;
     String someInformation;
     // any other information that you want to send back in case of exception.
}


@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.CONFLICT)  // 409
    @ResponseBody
    @ExceptionHandler(DataIntegrityViolationException.class)
    public APIResponse handleConflict(DataIntegrityViolationException exception) {
        APIResponse  response = createResponseFromException(exception);
        return response;
    }
}
Controller advice not handle my exception in Spring Boot 1.5.3

Controller advice not handle my exception in Spring Boot 1.5.3


By : lee zhiyang
Date : March 29 2020, 07:55 AM
should help you out Obviously @ControllerAdvice can't handle your exception because controller methods has not been called yet. I mean you exception being thrown in servlet filter. I think you going to have to catch it manually, smth like this:
code :
public class StatelessAuthenticationFilter extends GenericFilterBean {

    private final TokenAuthenticationService tokenAuthenticationService;

    public StatelessAuthenticationFilter(TokenAuthenticationService taService) {
        this.tokenAuthenticationService = taService;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        Authentication auth = null;
        try {
           auth = tokenAuthenticationService.getAuthentication((HttpServletRequest) req);
        } catch (MyOwnException e) {
            SecurityContextHolder.clearContext();
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(auth);
        chain.doFilter(req, res);
    }
How to handle exception in DeferredResult in Spring Boot?

How to handle exception in DeferredResult in Spring Boot?


By : Menoikeus
Date : March 29 2020, 07:55 AM
hope this fix your issue DeferredResult has method setErrorResult which can take Exception and according to the documentation:
Handle Embedded Tomcat Exception in Spring Boot

Handle Embedded Tomcat Exception in Spring Boot


By : KhushabuJariwala
Date : March 29 2020, 07:55 AM
will help you This is a feature of Tomcat itself as mentioned in this answer.
However, you can do something like this by allowing the special characters that you are expecting as part of your request and handle them yourself.
Spring boot - How to handle page not found exception using exception handler

Spring boot - How to handle page not found exception using exception handler


By : Leandro Alves
Date : March 29 2020, 07:55 AM
should help you out I think you can try this, at least it worked for me :
Add this two properties in the application.properties :
code :
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
@ExceptionHandler(value = NoHandlerFoundException.class)
public String exception(NoHandlerFoundException e, ...) {
Related Posts Related Posts :
  • Spring Security: Redirect to invalid-session-url instead of logout-success-url on successful logout
  • What happens on a JMS queue when onMessage() throws a JMSException?
  • How does Reactive programming using WebFlux handles dependent external api calls
  • Spring Kafka replay old messages
  • Spring boot + JMS + IBM MQ
  • What's mean that Caused by: javax.validation.ValidationException: Unable to find a default provider?
  • Autowire Annotation in Spring without using Component Scanning
  • Injecting Mockito mocks into a Spring bean
  • spring-security-oauth2 vs spring-security-oauth2-core in Spring
  • Ignore an Empty Request Body?
  • org.hibernate.hql.internal.ast.QuerySyntaxException: Employee is not mapped [from Employee];
  • Appropriate Oracle download for hibernate-dialect org.hibernate.dialect.Oracle9Dialect
  • spring boot https PKCS12 DerInputStream.getLength(): lengthTag=111, too big
  • JPA Native query puts parentheses wrong for List paremeter on INSERT INTO VALUES
  • How to connect JPARepository with ItemReader using spring batch?
  • Spring Data MongoDB + Spring Boot starting twice?
  • @Service vs @Component in Spring
  • Validation in spring boot rest controller
  • How Rest Controller handle multiple request at same time for a single instance application?
  • Error : java.lang.ClassNotFoundException: org.hibernate.cfg.AnnotationConfiguration
  • Does @Value support letting default value reference another @Value?
  • Spring boot 2: Fail to reach controller method
  • Execute state actions synchronously
  • How to access application.yml properties in Spring 1.5.9
  • CORS settings in Spring boot does not work
  • Spring boot log settings in application.yml
  • how to get KafkaListener Consumer
  • spring webflux webclient response convert list of string to string
  • What are this Spring version names?
  • Correct guide about spring Oauth 2
  • How does Spring Boot application with application.yml behave for when dependency also has an application.yml file
  • Spring batch unit testing job with external input and db output
  • Does Apache Camel replace or complement creating micro-services with Spring Boot?
  • Redis Cache memory Status
  • ConstraintValidator dependency injection leads to ValidationException when being validated at class level
  • How can I map the fields return in JSON with my entity provided the key in JSON has different name than fields in my ent
  • Content type 'application/x-www-form-urlencoded' not supported" for post method
  • How can i use Myfaces 2.3, Primefaces Elite 7.0.4 & Extensions and Omnifaces 3.3 together in a SpringBoot applicatio
  • Reactive WebClient of non-reactive remote server
  • Enable properties only for testing in Spring
  • PrematureCloseException: Connection prematurely closed
  • Spring application - Override app properties by test properties
  • Proper way to response nothing to ajax request on Spring
  • Spring Boot - Push message to Angular UI
  • Spring boot: path param is null
  • A UserDetailsService must be set Error in Spring Boot app
  • How does Spring convert config values with units to natural numbers
  • How to disconnect from rabbitmq after each test?
  • Autowiring of beans in spring boot with @Qualifier annotation
  • Spring Cloud Gateway not starting when deployed as WAR showing webFluxConversionService error
  • How to return response as Json from spring filter?
  • Spring OAuth2 ResourceServer dependency hell
  • How can I use @Transactional in multithreaded environment
  • Can not access controller.RestController for maven build
  • Spring Boot Tries to Access A Post Request URL but shows GET not supported
  • Jackson Mapping Issue
  • Kafka consumer not committing offset correctly
  • How does spring security maintain authentication information between request?
  • Best practice of Spring Security with user details storage in microservices
  • It takes too long to send response (http status) back with sending emails
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk