Error Handling: sendError(), setStatus(), and Custom Error Pages
Error Handling in Servlets
जब हम Servlet Programming करते हैं, तो कई बार ऐसे situations आते हैं जहाँ errors या exceptions हो जाते हैं। ये errors या तो client-side पर होते हैं या server-side पर। इसलिए, Java Servlet में Error Handling बहुत ज़रूरी concept है, ताकि user को friendly message दिखे और application crash न करे।
What is Error Handling?
Error Handling का मतलब है किसी भी unexpected error को handle करना ताकि user को proper information मिले और server को damage न पहुँचे। Servlet में error को handle करने के लिए हम sendError(), setStatus(), और Custom Error Pages का use करते हैं।
Types of Errors in Servlets
Servlets में दो तरह के errors commonly आते हैं:
- Client Side Error (4xx): जब client (जैसे browser) की request गलत होती है। उदाहरण: 404 (Page Not Found), 403 (Forbidden) आदि।
- Server Side Error (5xx): जब server-side code या configuration में problem होती है। उदाहरण: 500 (Internal Server Error)।
Using sendError() Method
sendError() method का use तब किया जाता है जब हम manually client को error message भेजना चाहते हैं। यह method HttpServletResponse interface में defined है।
Syntax:
response.sendError(int statusCode, String message);
Example:
if(username == null || username.isEmpty()) {
response.sendError(400, "Username is missing!");
} else {
// normal processing
}
ऊपर दिए गए example में अगर username null या empty है, तो server client को HTTP 400 Bad Request error भेजता है और message “Username is missing!” दिखाता है।
Using setStatus() Method
setStatus() method error को send नहीं करता, बल्कि response का status code set करता है। इसका use तब किया जाता है जब आप manually status set करना चाहते हैं लेकिन custom message भेजना नहीं चाहते।
Syntax:
response.setStatus(int statusCode);
Example:
if(!isValidUser) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
out.println("Access Denied: Invalid Credentials!");
} else {
response.setStatus(HttpServletResponse.SC_OK);
out.println("Welcome, User!");
}
यहाँ अगर user valid नहीं है, तो response status code 401 Unauthorized set होता है और user को friendly message दिखता है।
Custom Error Pages in Servlets
Custom Error Pages का मतलब है कि जब कोई specific error हो, तो server default error message की जगह एक user-friendly HTML page दिखाए। यह सबसे professional तरीका है error handle करने का।
Step 1: Define Error Page in web.xml
Servlet container को बताने के लिए कि कौन-से error पर कौन-सा page दिखाना है, हम web.xml file में configuration करते हैं।
Example web.xml:
<error-page>
<error-code>404</error-code>
<location>/error404.html</location>
</error-page>
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/error500.html</location>
</error-page>
ऊपर configuration में अगर 404 error होता है तो error404.html page दिखेगा, और अगर NullPointerException होती है तो error500.html page show होगा।
Step 2: Create Custom Error Pages
अब error404.html और error500.html pages बनाओ जो user को meaningful message दिखाएँ।
Example: error404.html
<html>
<head><title>Page Not Found</title></head>
<body>
<h2>Oops! The page you are looking for is not available.</h2>
<a href="/home">Go to Home Page</a>
</body>
</html>
Example: error500.html
<html>
<head><title>Server Error</title></head>
<body>
<h2>Something went wrong! Please try again later.</h2>
</body>
</html>
Exception Handling in Servlets
Java Servlet में exceptions को handle करने के लिए try-catch block का use किया जाता है। यह सबसे basic और effective तरीका है।
Example:
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
response.sendError(500, "Internal Server Error: Division by Zero");
}
यह code automatically 500 error भेजेगा जब exception होगी। इससे application crash नहीं होगा और user को clear message मिलेगा।
Difference between sendError() and setStatus()
| Feature | sendError() | setStatus() |
|---|---|---|
| Purpose | Send an actual error response to the client | Only set the status code in response |
| Custom Message | Can send custom message with status | Cannot send custom message directly |
| Browser Behavior | Browser shows default error page | Browser does not show error page automatically |
| Use Case | When you want to inform client about specific error | When you just want to update status (like success/failure) |
Best Practices for Error Handling
- Always use try-catch blocks for code that may throw exceptions।
- Never expose internal server details in error messages।
- Use Custom Error Pages for better user experience।
- Log every exception using frameworks like Log4j या SLF4J।
- Use meaningful HTTP status codes (200, 404, 500, etc.)।
Common HTTP Status Codes
| Status Code | Meaning | Description |
|---|---|---|
| 200 | OK | Request successfully completed। |
| 400 | Bad Request | Client request is invalid। |
| 401 | Unauthorized | User authentication required। |
| 403 | Forbidden | Access denied for the requested resource। |
| 404 | Not Found | Requested resource is not available। |
| 500 | Internal Server Error | Server encountered unexpected issue। |
Error Logging and Debugging
जब भी कोई exception या error आती है, उसे log करना बहुत ज़रूरी होता है। इससे developer बाद में analyze कर सकता है कि error कहाँ और क्यों आई।
Example:
try {
String data = null;
data.length(); // NullPointerException
} catch (NullPointerException e) {
log("NullPointerException occurred: " + e.getMessage());
response.sendError(500, "Server Error: Please contact admin.");
}
Summary of Error Handling
- sendError() — error को client तक भेजने के लिए।
- setStatus() — केवल status code set करने के लिए।
- Custom Error Pages — user experience improve करने के लिए।
- try-catch — exception को prevent करने के लिए।
- Logging — future debugging के लिए helpful होता है।
इन सभी techniques को follow करके आप अपने Servlet-based web application में efficient और professional error handling कर सकते हैं। इससे ना केवल user experience बेहतर होगा बल्कि आपकी site की reliability और SEO performance भी बढ़ेगी।