# API स्टेटस कोड व एरर हैंडलिंग — एडवांस्ड जावा

Source: https://www.geekswithgeeks.com/hi/advanced-java/adv-api-errors

> हर परिणाम के लिए सही HTTP स्टेटस लौटाएँ, और कंट्रोलर में try/catch बिखेरने के बजाय एक वैश्विक @ExceptionHandler से एरर रिस्पॉन्स केंद्रीकृत करें।

## स्टेटस कोड अनुबंध का हिस्सा हैं

सफलता के लिए `200 OK`, `201 Created`, `204 No Content`; क्लाइंट त्रुटि के लिए `400 Bad Request`, `401 Unauthorized`, `403 Forbidden`, `404 Not Found`, `409 Conflict`; अप्रत्याशित सर्वर विफलता के लिए `500 Internal Server Error`।

## एक वैश्विक exception handler

`@RestControllerAdvice` **हर** कंट्रोलर में exception-to-response मैपिंग केंद्रीकृत करता है — किसी कंट्रोलर को try/catch की ज़रूरत नहीं।

```java
@RestControllerAdvice
class ApiExceptionHandler {
    @ExceptionHandler(OrderNotFoundException.class)
    ResponseEntity<ErrorBody> notFound(OrderNotFoundException e) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
            .body(new ErrorBody("ORDER_NOT_FOUND", e.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    ResponseEntity<ErrorBody> badInput(MethodArgumentNotValidException e) {
        return ResponseEntity.badRequest()
            .body(new ErrorBody("VALIDATION_ERROR", e.getMessage()));
    }
}
```

स्टेटस कोड जाँच

**Quiz:** क्लाइंट वैध क्रेडेंशियल भेजता है पर किसी और के ऑर्डर को हटाने की कोशिश करता है। कौन-सा स्टेटस कोड सही है?

- [ ] 401 Unauthorized
- [ ] 404 Not Found
- [x] 403 Forbidden
- [ ] 500 Internal Server Error

*Answer:* 403 Forbidden. 401 का मतलब क्रेडेंशियल गायब/अमान्य है; यहाँ क्लाइंट प्रमाणित है पर इस resource पर कार्रवाई की अनुमति नहीं — यही 403 है।
