Ambiguous @ExceptionHandler method mapped for [class ProdusNegasitException]
Două metode @ExceptionHandler din aceeași clasă (controller sau @ControllerAdvice) tratează exact aceeași excepție, iar Spring nu poate alege. Păstrează un singur handler pentru fiecare tip de excepție.
Explicat de Tudor Andrei Dumitrescu, Senior Software Developer, fondatorul Academiei ProgramatorilorActualizat la
Ce înseamnă
Spring construiește, pentru fiecare controller și pentru fiecare @ControllerAdvice, o tabelă excepție → metodă. Dacă două metode din aceeași clasă declară același tip (@ExceptionHandler(ProdusNegasitException.class) de două ori, sau o metodă cu tipul în adnotare și alta cu el ca parametru), Spring aruncă la pornire IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class ProdusNegasitException], urmat de cele două metode.
Nu e o problemă când tipurile sunt diferite, chiar înrudite: pentru ProdusNegasitException și RuntimeException, Spring alege handler-ul cel mai specific. De asemenea, un handler în controller și unul în @ControllerAdvice pentru același tip nu sunt în conflict: cel din controller are prioritate pentru rutele lui.
Apare de obicei după ce copiezi un handler, sau când mai mulți colegi adaugă handler-e în același advice.
De ce apare: cauzele frecvente
1Același tip tratat de două ori
@ExceptionHandler(ProdusNegasitException.class)
ResponseEntity<String> a(ProdusNegasitException e) { ... }
@ExceptionHandler(ProdusNegasitException.class)
ResponseEntity<String> b(ProdusNegasitException e) { ... }@ExceptionHandler(ProdusNegasitException.class)
ResponseEntity<String> produsNegasit(ProdusNegasitException e) { ... }Un singur handler pe tip, în aceeași clasă.
2Tip dedus din parametru, în plus față de adnotare
@ExceptionHandler
String x(ProdusNegasitException e) { ... }
@ExceptionHandler({ProdusNegasitException.class, StocException.class})
String y(RuntimeException e) { ... }@ExceptionHandler
String x(ProdusNegasitException e) { ... }
@ExceptionHandler(StocException.class)
String y(StocException e) { ... }Fără argumente, @ExceptionHandler ia tipul din parametru; verifică să nu se suprapună cu altă listă.
Repară eroarea, direct în pagină
ProdusController are două metode @ExceptionHandler(ProdusNegasitException.class), una veche (răspunde 500 cu Eroare) și una nouă (404 cu mesajul excepției). În Spring Boot real aplicația nu pornește: Ambiguous @ExceptionHandler method mapped. Șterge handler-ul vechi, ca GET /produse/9 să răspundă 404 cu Produsul 9 nu există.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.http.*;
import java.util.*;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
class ProdusNegasitException extends RuntimeException {
ProdusNegasitException(long id) {
super("Produsul " + id + " nu există");
}
}
@RestController
class ProdusController {
@GetMapping("/produse/{id}")
String unul(@PathVariable long id) {
if (id != 1) {
throw new ProdusNegasitException(id);
}
return "Mouse";
}
@ExceptionHandler(ProdusNegasitException.class)
ResponseEntity<String> vechi(ProdusNegasitException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Eroare");
}
@ExceptionHandler(ProdusNegasitException.class)
ResponseEntity<String> produsNegasit(ProdusNegasitException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
}
}Tomcat started on port 8080 (http) Started Application GET /produse/1 → 200 Mouse GET /produse/9 → 404 Produsul 9 nu există
Indiciu
Păstrează doar handler-ul care întoarce HttpStatus.NOT_FOUND.
Reparația
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.http.*;
import java.util.*;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
class ProdusNegasitException extends RuntimeException {
ProdusNegasitException(long id) {
super("Produsul " + id + " nu există");
}
}
@RestController
class ProdusController {
@GetMapping("/produse/{id}")
String unul(@PathVariable long id) {
if (id != 1) {
throw new ProdusNegasitException(id);
}
return "Mouse";
}
@ExceptionHandler(ProdusNegasitException.class)
ResponseEntity<String> produsNegasit(ProdusNegasitException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
}
}De ce merge
Două metode din aceeași clasă pretindeau aceeași excepție. Spring Boot real refuză să pornească (Ambiguous @ExceptionHandler method); laboratorul o alegea pe prima, cea veche, de aceea primeai 500. Cu un singur handler, alegerea e clară: ProdusNegasitException produce 404 cu mesajul ei. Regula: un handler per tip de excepție, în fiecare clasă.
Alte forme ale mesajului
java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.bind.MethodArgumentNotValidException]
Cum o eviți pe viitor
- Ține handler-ele globale într-un singur
@RestControllerAdvice, ordonate pe tipuri. - Caută în proiect tipul excepției înainte să adaugi un handler nou.
- Dacă extinzi
ResponseEntityExceptionHandler, nu adăuga@ExceptionHandlerpentru excepțiile pe care le tratează deja (de exempluMethodArgumentNotValidException): suprascrie metoda lui.
Întrebări frecvente
Pot avea handler pentru RuntimeException și pentru o subclasă?
Da. Spring alege handler-ul cu tipul cel mai apropiat de excepția aruncată.
De ce apare cu MethodArgumentNotValidException?
Pentru că ResponseEntityExceptionHandler o tratează deja. Dacă advice-ul tău îl extinde și adaugă propriul @ExceptionHandler pentru ea, apar două metode pe același tip.
Erori înrudite
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.IllegalStateException: Stoc insuficient pentru Mouse] with root cause O excepție aruncată din controller sau serviciu nu a fost tratată nicăieri, a ajuns până la servlet, iar clientul a primit 500. Excepția reală e în paranteze și în stiva de sub mesaj. Repar-o sau trateaz-o cu un @ExceptionHandler care întoarce statusul potrivit. There was an unexpected error (type=Internal Server Error, status=500). Rândul din pagina Whitelabel spune că o excepție netratată a produs 500. Cauza e în log. Pentru excepțiile tale de business, adaugă @ResponseStatus pe clasa excepției sau un @ExceptionHandler, ca să răspunzi cu codul potrivit (404, 409). "message": "No message available" Răspunsul de eroare implicit al Spring Boot nu conține mesajul excepției: de la Boot 2.3, message este ascuns (sau apare ca „No message available” / gol). Activează server.error.include-message=always în dezvoltare sau întoarce mesajul explicit, de exemplu cu ProblemDetail. Învață Spring Boot de la zero, cu exerciții la fiecare lecție
Curs Spring Boot și REST API: lecții scurte, fiecare cu un exercițiu verificat automat, direct în browser. Primele 18 lecții sunt gratuite.
