Introduction
A REST API is not complete simply because it returns a successful response.
A production-ready API must also handle failures in a predictable and meaningful way.
Consider a SAP Commerce OCC API:
GET /occ/v2/electronics/customproducts/P999What should happen when product P999 doesn't exist?
Should the API return:
500 Internal Server ErrorProbably not.
A better response would indicate that the requested resource could not be found.
Similarly, if a customer sends invalid data, the API should return a client-side error rather than a generic server exception.
This is why OCC error handling is an important part of SAP Commerce development.
In this article, we'll cover:
- SAP Commerce OCC exception handling
- Common exceptions
- HTTP status codes
- Error DTOs
- Validation errors
- Global error handling
- Custom exceptions
- Authentication and authorization errors
- Postman testing
- Troubleshooting strategies
- Interview questions
- Enterprise best practices
What is OCC Error Handling?
OCC error handling is the mechanism used by SAP Commerce to convert application exceptions into structured HTTP responses.
A simplified flow is:
Client
↓
OCC Controller
↓
Facade
↓
Service
↓
DAO
↓
Exception
↓
OCC Error Handling
↓
HTTP Error Response
↓
ClientInstead of exposing internal Java stack traces, the API should return a controlled response.
For example:
{
"errors": [
{
"type": "UnknownIdentifierError",
"message": "Product not found"
}
]
}The exact response fields depend on the SAP Commerce version and configured OCC error-handling implementation.
Why Error Handling Matters
Good error handling provides:
- Consistent API responses
- Easier client-side handling
- Better debugging
- Improved security
- Better user experience
- Clearer monitoring
- Easier integration testing
Poor error handling can expose internal implementation details and make production troubleshooting much harder.
Common HTTP Status Codes
A well-designed API uses appropriate HTTP status codes.
| Status | Meaning | Typical OCC Scenario |
|---|---|---|
| 200 | OK | Successful GET |
| 201 | Created | Successful resource creation |
| 204 | No Content | Successful operation with no response body |
| 400 | Bad Request | Invalid request |
| 401 | Unauthorized | Authentication missing/invalid |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource doesn't exist |
| 409 | Conflict | Business/data conflict |
| 500 | Internal Server Error | Unexpected server failure |
200 OK
A successful GET commonly returns:
200 OKExample:
GET /occ/v2/electronics/products/P100Response:
{
"code": "P100",
"name": "Laptop"
}201 Created
A successful create operation can return:
201 CreatedFor example:
POST /occ/v2/electronics/usersafter successfully creating a customer.
204 No Content
Some successful operations don't need to return a response body.
For example:
DELETE /resource/123could return:
204 No Contentdepending on the endpoint implementation.
400 Bad Request
A 400 indicates that the client sent an invalid request.
Examples:
Missing required field
Invalid JSON
Invalid parameter
Invalid value
Malformed requestExample:
{
"email": "invalid-email"
}if the endpoint requires a valid email address.
401 Unauthorized
A 401 generally indicates an authentication problem.
Typical causes:
- Missing access token
- Expired token
- Invalid token
- Invalid authentication configuration
Example:
GET /occ/v2/electronics/users/current/orderswithout a valid access token.
403 Forbidden
A 403 generally means that authentication succeeded but authorization failed.
For example:
Authenticated customer
↓
Attempts admin-only API
↓
403 ForbiddenRemember:
401 = Authentication problem
403 = Authorization problemThis is one of the most common OCC interview questions.
404 Not Found
Use 404 when the requested resource doesn't exist.
For example:
GET /occ/v2/electronics/products/UNKNOWNIf no product exists for that code, the API should return an appropriate not-found response.
409 Conflict
409 Conflict can be useful when the request conflicts with the current state of a resource.
Examples include:
- Duplicate business identifier
- Invalid state transition
- Resource already exists
- Concurrent update conflict
Whether a particular OCC endpoint uses 409 depends on its implementation and error mapping.
500 Internal Server Error
A 500 should generally indicate an unexpected server-side failure.
Examples:
- Unhandled exception
- Database failure
- External service failure
- Programming error
Do not intentionally return 500 for normal validation or not-found conditions.
Common SAP Commerce Exceptions
During OCC execution, various SAP Commerce exceptions may occur.
Common examples include:
UnknownIdentifierException
ModelNotFoundException
InterceptorException
ValidationException
IllegalArgumentException
CommerceCartModificationExceptionThe exact exceptions depend on the service being called.
UnknownIdentifierException
Suppose an API retrieves a product by code:
ProductModel product =
productService.getProductForCode(code);If the product cannot be found, the service layer can throw an appropriate identifier-related exception.
Conceptually:
if (product == null)
{
throw new UnknownIdentifierException(
"Product not found: " + code);
}The OCC layer can then translate this into an appropriate REST error response.
ModelNotFoundException
This exception can occur when a requested model cannot be found in situations where the underlying API expects it to exist.
For example:
Order
Customer
Product
CartWhen exposing these resources through OCC, the exception should be transformed into a client-friendly response rather than leaking internal details.
ValidationException
Validation exceptions can occur when request data or model data fails validation.
For example:
Email missing
Invalid date
Missing mandatory field
Invalid business valueA good API should communicate clearly which input caused the failure.
InterceptorException
SAP Commerce interceptors can reject model operations.
For example:
PrepareInterceptor
ValidateInterceptor
RemoveInterceptorSuppose an attribute is mandatory:
externalIdand the model is saved without it.
A validation or interceptor-related exception may be raised.
That exception should be handled appropriately at the application boundary.
OCC Error Response
A typical structured error response can look like:
{
"errors": [
{
"type": "UnknownIdentifierError",
"message": "Product P999 was not found"
}
]
}Depending on the version and configuration, an OCC error response can contain additional information such as:
type
message
reason
subject
subjectType
languageThe exact schema should be verified against the OCC version used by the project.
Why Should We Return Structured Errors?
Imagine your frontend receives:
500 Internal Server Errorwith no useful information.
The developer has no idea what happened.
Compare that with:
{
"errors": [
{
"type": "UnknownIdentifierError",
"message": "Product P999 was not found"
}
]
}Now the client can handle the error appropriately.
Exception Mapping
The OCC layer maps Java exceptions to HTTP errors.
Conceptually:
UnknownIdentifierException
↓
404
↓
UnknownIdentifierErrorAnother example:
AuthenticationException
↓
401and:
AccessDeniedException
↓
403The exact mappings depend on the configured SAP Commerce security and exception-handling infrastructure.
Error Handling in Controller
Avoid putting large amounts of exception-handling logic into every controller.
For example, don't repeat this everywhere:
try
{
// business logic
}
catch (Exception e)
{
// manually construct response
}A centralized exception-handling mechanism is generally easier to maintain.
Global Exception Handling
A global exception handler can provide a central place to handle errors.
In Spring-based applications, concepts such as:
@ControllerAdviceand:
@ExceptionHandlerare commonly used for centralized MVC exception handling.
A simplified example:
@ControllerAdvice
public class GlobalExceptionHandler
{
@ExceptionHandler(
UnknownIdentifierException.class)
public ResponseEntity<?> handleNotFound(
UnknownIdentifierException exception)
{
// Build appropriate response
return ResponseEntity.notFound().build();
}
}However, in SAP Commerce OCC projects, you should first understand and use the platform's existing OCC exception-handling mechanisms rather than introducing a parallel error framework unnecessarily.
Custom OCC Exceptions
Sometimes a business requirement needs a specific error.
For example:
Cannot cancel an already shipped orderInstead of returning:
500you can define appropriate business exception handling.
Conceptually:
throw new InvalidOrderStateException(
"Order cannot be cancelled after shipment");The OCC layer can then translate the exception into a structured error response.
Example: Cancel Order
Suppose:
Order status = SHIPPEDand the customer tries:
POST /orders/123/cancelThe service checks:
if (OrderStatus.SHIPPED.equals(order.getStatus()))
{
throw new InvalidOrderStateException(
"Shipped orders cannot be cancelled");
}The API should return a meaningful client-facing error rather than a generic 500.
Validation Errors
Suppose we have:
{
"firstName": "",
"email": "abc"
}If the endpoint requires:
firstName → mandatory
email → valid formatthe API should identify the invalid fields.
Conceptually:
{
"errors": [
{
"type": "ValidationError",
"message": "First name is required",
"subject": "firstName"
},
{
"type": "ValidationError",
"message": "Invalid email address",
"subject": "email"
}
]
}The exact representation depends on the project's OCC validation configuration.
Don't Expose Stack Traces
Never return:
{
"stackTrace": "java.lang.NullPointerException..."
}to a customer or external client.
Stack traces can reveal:
- Internal class names
- File paths
- Database details
- Infrastructure details
- Security-sensitive information
Log diagnostic information internally and return a controlled API response.
Logging Errors
A useful production log should capture:
Request ID
Endpoint
HTTP method
User/client
Exception type
Error message
Timestamp
Correlation IDExample:
RequestId=REQ-10001
Endpoint=/occ/v2/electronics/products/P999
Exception=UnknownIdentifierException
Product=P999Do not log:
Passwords
OAuth tokens
Client secrets
Sensitive customer informationError Handling with Postman
Postman is useful for validating OCC error behaviour.
Test 1: Invalid Product
Request:
GET /occ/v2/electronics/products/P999Expected:
404 Not FoundTest 2: No Authentication
Request:
GET /occ/v2/electronics/users/current/orderswithout a token.
Expected:
401 UnauthorizedTest 3: Insufficient Permission
Use a valid authenticated user without the required permission.
Expected:
403 ForbiddenTest 4: Invalid Request
Send incomplete request data.
Expected:
400 Bad RequestError Handling in CI/CD
Automated API tests should validate both:
Success scenarios
Failure scenariosFor example:
Product exists → 200
Product missing → 404
Invalid request → 400
Missing token → 401
Insufficient permission → 403This prevents accidental changes to your API contract.
Error Handling Test Matrix
| Scenario | Expected Status |
|---|---|
| Valid product | 200 |
| Product not found | 404 |
| Invalid request | 400 |
| Missing token | 401 |
| Invalid permissions | 403 |
| Successful create | 201 |
| Successful delete | 204 |
| Unexpected server failure | 500 |
This table can become a useful regression checklist.
Common Mistakes
Returning 500 for Everything
Bad:
Product not found → 500
Invalid input → 500
Unauthorized → 500This makes the API difficult to consume.
Catching Exception Too Broadly
Avoid:
catch (Exception e)
{
throw new RuntimeException();
}This can hide the actual business error.
Swallowing Exceptions
Avoid:
try
{
// operation
}
catch (Exception e)
{
// do nothing
}Failures must be logged and handled appropriately.
Exposing Internal Messages
Avoid returning:
SQL Exception
Database table doesn't exist
NullPointerExceptiondirectly to API consumers.
Best Practices
Use Meaningful HTTP Status Codes
Don't use 500 for client errors.
Keep Error Responses Consistent
Clients should receive a predictable structure.
Centralize Common Error Handling
Use the platform's OCC mechanisms and Spring error-handling facilities appropriately.
Log Internally
Capture detailed diagnostics in server logs.
Protect Sensitive Information
Never expose credentials, tokens or internal infrastructure details.
Test Failure Scenarios
Negative scenarios are just as important as happy-path scenarios.
Enterprise Example
Imagine a checkout API:
POST /occ/v2/electronics/users/current/carts/123/paymentPossible outcomes:
Valid payment
↓
200 / 201
Invalid payment data
↓
400
Not authenticated
↓
401
Not authorized
↓
403
Cart doesn't exist
↓
404
Payment state conflict
↓
409
Payment service failure
↓
500This makes the API predictable for the storefront or mobile application.
Interview Questions
What is OCC error handling?
It is the mechanism that converts backend exceptions into appropriate HTTP responses and structured OCC error information.
What is the difference between 400 and 500?
400 generally indicates that the request from the client is invalid, while 500 indicates an unexpected server-side failure.
What is the difference between 401 and 403?
401 indicates an authentication problem. 403 means the caller is authenticated but does not have sufficient permission.
What should happen when a product doesn't exist?
The API should normally return a not-found response such as:
404 Not Foundwith an appropriate structured error.
Should stack traces be returned to API clients?
No. Detailed stack traces should remain on the server side.
Where should business validation occur?
Business validation generally belongs in the appropriate Service Layer/domain logic, while request-shape validation can happen at the API boundary.
Should every controller have its own try-catch?
No. Centralized exception handling is generally easier to maintain. Use SAP Commerce's existing OCC exception-handling facilities where applicable.
Real Interview Scenario
Question
Your custom OCC API returns 500 when a product code doesn't exist. How would you fix it?
Answer
I would first inspect the service and DAO flow.
Controller
↓
Facade
↓
Service
↓
DAOThen determine how the missing product is represented.
Instead of allowing a generic exception or null-pointer failure to reach the web layer, the service should use an appropriate identifier-related exception.
The OCC error-handling mechanism can then map that exception to a suitable 404 response and structured error payload.
I would also add an automated regression test for the missing-product scenario.
Another Interview Scenario
Question
The API returns 401 even though Postman has a token.
What would you investigate?
Answer
I would check:
Token expiration
Token format
Authorization header
Bearer prefix
OAuth client
Scope/roles
Endpoint security configuration
Environment-specific OAuth configuration
Clock differencesAnother Interview Scenario
Question
The API returns 403 after a successful login.
What does that tell you?
Answer
Authentication likely succeeded, but authorization failed.
I would investigate:
Client roles
User roles
Endpoint restrictions
Spring Security configuration
Required OCC roleComplete Error-Handling Architecture
Remember this flow:
CLIENT
|
↓
OCC Controller
|
↓
Facade
|
↓
Service
|
↓
DAO
|
↓
Exception
|
↓
OCC Error Handling
|
┌─────────────┼──────────────┐
↓ ↓ ↓
400 404 500
Bad Request Not Found Server Error
|
↓
Structured Error
|
↓
CLIENTFor security-related failures:
Authentication Failure → 401
Authorization Failure → 403Conclusion
Good error handling is a critical part of a production-ready SAP Commerce OCC API.
The most important principles are:
Correct Exception
↓
Correct HTTP Status
↓
Structured Error Response
↓
Useful Server Logging
↓
Secure Client ResponseIn this article, we covered:
- OCC exception handling
- HTTP status codes
400,401,403,404,409, and500- Common SAP Commerce exceptions
- Validation errors
- Global exception handling
- Custom business exceptions
- Postman testing
- CI/CD validation
- Security considerations
- Production troubleshooting
- Interview scenarios
The goal is not simply to prevent an exception from crashing an API. The goal is to make the API predictable, secure, debuggable, and easy for client applications to consume.