Descripción
Create a global exception handler using @ControllerAdvice with example methods
File Template: ✅
Prefix
spring:exhandler:global
Scopes
java
Snippet de código
package ${1:com.example.demo.exception};
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class ${2:GlobalExceptionHandler} {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex, WebRequest request) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}
// Example: NotFoundException
@ExceptionHandler(${3:ResourceNotFoundException}.class)
public ResponseEntity<String> handleNotFound(${3:ResourceNotFoundException} ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}