Java: Global Exception Handler

Java: Global Exception Handler

Use Thread.setDefaultUncaughtExceptionHandler. See Rod Hilton's "Global Exception Handling" blog post for an example.

How to handle global exceptions in java spring?

Make it a component and set the derault exception handler in an @PostContruct method.

@Component
public class GlobalExceptionHandler implements Thread.UncaughtExceptionHandler{

@Autowired
private LoggedExceptionService service;

public GlobalExceptionHandler() {
}

@PostContruct
public void init(){
Thread.setDefaultUncaughtExceptionHandler(this);
}

@Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println("IN UNCAUGHTEXCEPTION METHOD");
this.service.saveException(new LoggedException(e));
}
}

This allows you to automatically set the handler as methods annotated with @PostContruct in components are automatically executed on startup.

Making GlobalExceptionHandler a spring component also allows to autowire service that would never been set otherwise. Anyways, I would recommend you to usd constructor autowiring:

@Component
public class GlobalExceptionHandler implements Thread.UncaughtExceptionHandler{

private final LoggedExceptionService service;

@Autowired // @Autowired is actually not necessary if this is the only constructor
public GlobalExceptionHandler(LoggedExceptionService service) {
this.service=service
}

@PostContruct
public void init(){
Thread.setDefaultUncaughtExceptionHandler(this);
}

@Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println("IN UNCAUGHTEXCEPTION METHOD");
this.service.saveException(new LoggedException(e));
}
}

Customize Global Exception Handler in java Spring Boot

You would need to extend ResponseEntityExceptionHandler as follows:

@ControllerAdvice("uz.pdp.warehouse")
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler({RuntimeException.class})
public ResponseEntity<DataDto<AppError>> handle500(RuntimeException e, WebRequest webRequest) {
return new ResponseEntity<>(
new DataDto<>(AppErrorDto.builder()
.message(e.getMessage())
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.path(webRequest.getContextPath())
.build()));
}

}

Global error handling for spring standalone application

Spring does not support global exception handler for standalone / non-mvc. As explained here you may need to implement it by defining jointpoint and pointcuts and enable pointcut for any "*Exception".



Related Topics



Leave a reply



Submit