RESOLVE
in rest api application, the return type of exception handling method should be ResponseEntity
or annotate the method with @ResponseBody
so that spring boot can do the http serialisation.
UPDATE
starter class:
@SpringBootApplication
@ComponentScan
@EnableAutoConfiguration
@EnableConfigurationProperties
@EnableTransactionManagement//TODO remove this line if not needed
public class Application extends SpringBootServletInitializer{
private static Class<Application> applicationClass= Application.class;
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(applicationClass);
}
}
I was using @ControllerAdvice
to handle global exception handling in spring boot starter web and I got such a weird problem.
As I followed the guide from spring official doc, https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc , to handling exceptions globally, just add a handler class with @ControllerAdivce
annotated. But, when I test it, the exception handling method is not invoked when a RunTimeException
is thrown.
Here is My code:
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(value = RuntimeException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public RestEntity handleException(HttpServletRequest req, RuntimeException ex) {
RestEntity restEntity=new RestEntity();
Message message=new Message();
message.setCode(1000);
message.setMessage("Something wrong with the server");
restEntity.setMessage(message);
return restEntity;
}
}
And I have methods in other controllers annotated with @ExceptionHandler
to handle specific exceptions in each Controller, while leave unresolved exceptions to the GlobalDefaultExceptionHandler
.
It turns out that it doesn't work. Am I missing something here??
And, for now, as a workaround , I just add @RestControoler
on the GlobalDefaultExceptionHandler
and it just work fine. I don't why...
Anyone can help?
I actually had to remove @EnableWebMvc from my main application file.
Here the working configuration for me:
@SpringBootApplication
@ComponentScan(basePackages = {
....
})
public class Application extends SpringBootServletInitializer { ... }
and the ControllerAdvice:
@ControllerAdvice
public class ErrorHandlingController { ... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.