Thursday, September 3, 2026

SAP Commerce OCC Error Handling: Exception Handling, Error DTOs, HTTP Status Codes & Global Error Handling

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/P999

What should happen when product P999 doesn't exist?

Should the API return:

500 Internal Server Error

Probably 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
  ↓
Client

Instead 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.

StatusMeaningTypical OCC Scenario
200OKSuccessful GET
201CreatedSuccessful resource creation
204No ContentSuccessful operation with no response body
400Bad RequestInvalid request
401UnauthorizedAuthentication missing/invalid
403ForbiddenInsufficient permissions
404Not FoundResource doesn't exist
409ConflictBusiness/data conflict
500Internal Server ErrorUnexpected server failure

200 OK

A successful GET commonly returns:

200 OK

Example:

GET /occ/v2/electronics/products/P100

Response:

{
  "code": "P100",
  "name": "Laptop"
}

201 Created

A successful create operation can return:

201 Created

For example:

POST /occ/v2/electronics/users

after successfully creating a customer.


204 No Content

Some successful operations don't need to return a response body.

For example:

DELETE /resource/123

could return:

204 No Content

depending 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 request

Example:

{
  "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/orders

without 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 Forbidden

Remember:

401 = Authentication problem
403 = Authorization problem

This 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/UNKNOWN

If 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
CommerceCartModificationException

The 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
Cart

When 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 value

A good API should communicate clearly which input caused the failure.


InterceptorException

SAP Commerce interceptors can reject model operations.

For example:

PrepareInterceptor
ValidateInterceptor
RemoveInterceptor

Suppose an attribute is mandatory:

externalId

and 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
language

The 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 Error

with 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
        ↓
UnknownIdentifierError

Another example:

AuthenticationException
        ↓
401

and:

AccessDeniedException
        ↓
403

The 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:

@ControllerAdvice

and:

@ExceptionHandler

are 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 order

Instead of returning:

500

you 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 = SHIPPED

and the customer tries:

POST /orders/123/cancel

The 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 format

the 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 ID

Example:

RequestId=REQ-10001
Endpoint=/occ/v2/electronics/products/P999
Exception=UnknownIdentifierException
Product=P999

Do not log:

Passwords
OAuth tokens
Client secrets
Sensitive customer information

Error Handling with Postman

Postman is useful for validating OCC error behaviour.

Test 1: Invalid Product

Request:

GET /occ/v2/electronics/products/P999

Expected:

404 Not Found

Test 2: No Authentication

Request:

GET /occ/v2/electronics/users/current/orders

without a token.

Expected:

401 Unauthorized

Test 3: Insufficient Permission

Use a valid authenticated user without the required permission.

Expected:

403 Forbidden

Test 4: Invalid Request

Send incomplete request data.

Expected:

400 Bad Request

Error Handling in CI/CD

Automated API tests should validate both:

Success scenarios
Failure scenarios

For example:

Product exists → 200
Product missing → 404
Invalid request → 400
Missing token → 401
Insufficient permission → 403

This prevents accidental changes to your API contract.


Error Handling Test Matrix

ScenarioExpected Status
Valid product200
Product not found404
Invalid request400
Missing token401
Invalid permissions403
Successful create201
Successful delete204
Unexpected server failure500

This table can become a useful regression checklist.


Common Mistakes

Returning 500 for Everything

Bad:

Product not found → 500
Invalid input → 500
Unauthorized → 500

This 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
NullPointerException

directly 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/payment

Possible 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
        ↓
500

This 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 Found

with 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
   ↓
DAO

Then 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 differences

Another 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 role

Complete 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
              |
              ↓
            CLIENT

For security-related failures:

Authentication Failure → 401
Authorization Failure  → 403

Conclusion

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 Response

In this article, we covered:

  • OCC exception handling
  • HTTP status codes
  • 400, 401, 403, 404, 409, and 500
  • 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.

No comments:

Post a Comment