Video tayyorlanmoqda

Junior 🌱 Spring

Controller'larda chiqqan exception'larni qanday qilib bitta joyda ushlab, chiroyli javob qaytarasiz?

@RestControllerAdvice klassida @ExceptionHandler metodlar yozasiz: har exception turi uchun status va javob body'si bitta joyda turadi.

📖 Javob

Har controller'da try/catch yozib o'tirmasdan:

@RestControllerAdvice
public class ApiErrors {

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ProblemDetail notFound(NotFoundException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail invalid(MethodArgumentNotValidException e) {
        ProblemDetail p = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        p.setProperty("fields", e.getBindingResult().getFieldErrors().stream()
                .map(f -> f.getField() + ": " + f.getDefaultMessage()).toList());
        return p;
    }
}

ProblemDetail (Spring 6) — RFC 9457 bo'yicha standart xato formati: type, title, status, detail.

Kutilmagan Exception uchun ham handler qo'ying, lekin mijozga stack trace yoki SQL xatosini yubormang. Uni logga yozasiz, mijozga esa umumiy "ichki xato" xabari va so'rov id'si boradi — keyin shu id bo'yicha logdan topasiz.