Skip to lesson

Custom exceptions such as NotFound and Conflict

ShopLite's service finds that a product is missing, a SKU is taken or a category is unknown. If it throws a plain RuntimeException each time, nothing downstream can tell these three failures apart.

ResourceNotFoundException, ConflictException and BusinessRuleException

A custom exception is your own exception class whose name says what went wrong, such as ResourceNotFoundException. Its type tells the rest of the app which kind of failure happened, and that later decides the HTTP status.

One small class per kind of failure. The demo throws all three from a catalog and prints the status each one will become.

Example 1 · One exception per kind of failure

CustomExceptionsDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.Set;
class ResourceNotFoundException extends RuntimeException {    ResourceNotFoundException(String resource, long id) {        super(resource + " " + id + " was not found.");    }}
class ConflictException extends RuntimeException {    ConflictException(String message) {        super(message);    }}
class BusinessRuleException extends RuntimeException {    BusinessRuleException(String message) {        super(message);    }}
class ProductCatalog {    private final Map<Long, String> skuById = new HashMap<>(Map.of(1L, "MOB-RN13", 3L, "MOB-IP15"));    private final Set<Long> categoryIds = Set.of(2L, 4L, 5L);    private long nextId = 16;
    String findSku(long id) {        String sku = skuById.get(id);        if (sku == null) {            throw new ResourceNotFoundException("Product", id);        }        return sku;    }
    long add(String sku, long categoryId) {        if (!categoryIds.contains(categoryId)) {            throw new BusinessRuleException("Category " + categoryId + " does not exist.");        }        if (skuById.containsValue(sku)) {            throw new ConflictException("A product with SKU " + sku + " already exists.");        }        long id = nextId++;        skuById.put(id, sku);        return id;    }}
public class CustomExceptionsDemo {
    public static void main(String[] args) {        ProductCatalog catalog = new ProductCatalog();        System.out.println("Found: " + catalog.findSku(1));        System.out.println("Added with id " + catalog.add("ACC-KB100", 4));
        attempt(() -> catalog.findSku(99));        attempt(() -> catalog.add("MOB-RN13", 4));        attempt(() -> catalog.add("ACC-KB200", 42));    }
    static void attempt(Runnable action) {        try {            action.run();        } catch (ResourceNotFoundException e) {            System.out.println("404 " + e.getMessage());        } catch (ConflictException e) {            System.out.println("409 " + e.getMessage());        } catch (BusinessRuleException e) {            System.out.println("422 " + e.getMessage());        }    }}
Output
Found: MOB-RN13
Added with id 16
404 Product 99 was not found.
409 A product with SKU MOB-RN13 already exists.
422 Category 42 does not exist.

What this code does

  • ProductCatalog throws a different exception for each kind of failure. The caller tells them apart by type alone, with no if on message text.
  • attempt turns each type into the status it will become in the API: 404, 409 and 422. A global handler does the same job in Spring, in one place.
  • The happy path still works: findSku(1) and add("ACC-KB100", 4) return values, and exceptions appear only for the failures.

ShopLite needs three kinds of failure:

  • ResourceNotFoundException: the thing in the URL does not exist (404).
  • ConflictException: the request clashes with the data as it is now, such as a duplicate SKU (409).
  • BusinessRuleException: every field is fine, but a rule involving other data is broken, such as an unknown category id (422).

Make them unchecked: extend RuntimeException. Callers need no throws or catch at every level, and the exception can travel from the service up to one central handler. With plain RuntimeException everywhere, a missing product looks like a real bug and every failure becomes the same 500.

A small hierarchy with a ShopLite base exception

ShopLiteException is the abstract parent of every error ShopLite expects and can explain to a client. ResourceNotFoundException, ConflictException and BusinessRuleException extend it, so one type means "a known error".

The whole family in the shared common package, with a small JUnit test that pins the rules.

The ShopLite exception family. ShopLiteException is the abstract parent. Under it: ResourceNotFoundException (404), the abstract ConflictException (409) with AlreadyExistsException and OutOfStockException below it, and BusinessRuleException (422).

Example 2 · The ShopLite exception family in common

Runs in: the errors-lab practice project (Spring Boot 4.1)

ShopLiteException.javaJava
package com.shoplite.lab.common;
/** Parent of every error ShopLite expects and can explain to a client. */public abstract class ShopLiteException extends RuntimeException {
    protected ShopLiteException(String message) {        super(message);    }
    protected ShopLiteException(String message, Throwable cause) {        super(message, cause);    }}
package com.shoplite.lab.common;
/** The resource named in the URL does not exist. */public class ResourceNotFoundException extends ShopLiteException {
    private final String resource;    private final Object id;
    public ResourceNotFoundException(String resource, Object id) {        super(resource + " " + id + " was not found.");        this.resource = resource;        this.id = id;    }
    public String getResource() {        return resource;    }
    public Object getId() {        return id;    }}
package com.shoplite.lab.common;
/** The request clashes with the current state of the data. */public abstract class ConflictException extends ShopLiteException {
    protected ConflictException(String message) {        super(message);    }}
package com.shoplite.lab.common;
/** A duplicate of something that must be unique: a SKU, an e-mail, a category name. */public class AlreadyExistsException extends ConflictException {
    public AlreadyExistsException(String message) {        super(message);    }}
package com.shoplite.lab.common;
/** Valid fields that break a rule involving other data, such as an unknown category. */public class BusinessRuleException extends ShopLiteException {
    public BusinessRuleException(String message) {        super(message);    }}
package com.shoplite.lab.common;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class ShopLiteExceptionTest {
    @Test    void notFoundMessageNamesTheResourceAndId() {        ResourceNotFoundException e = new ResourceNotFoundException("Product", 99L);
        assertThat(e).hasMessage("Product 99 was not found.");        assertThat(e.getResource()).isEqualTo("Product");        assertThat(e.getId()).isEqualTo(99L);    }
    @Test    void everyShopLiteErrorIsUnchecked() {        assertThat(new AlreadyExistsException("A product with SKU MOB-RN13 already exists."))                .isInstanceOf(ConflictException.class)                .isInstanceOf(ShopLiteException.class)                .isInstanceOf(RuntimeException.class);        assertThat(new BusinessRuleException("Category 42 does not exist."))                .isInstanceOf(ShopLiteException.class);    }}
Sample output
$ mvn test
...
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.shoplite.lab.common.ShopLiteExceptionTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.271 s -- in com.shoplite.lab.common.ShopLiteExceptionTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

What this code does

  • ShopLiteException and ConflictException are abstract with protected constructors, so code must throw a specific kind such as AlreadyExistsException.
  • ResourceNotFoundException builds its own message from the resource name and id, and keeps both as fields for later use.
  • The small JUnit test pins the message format and checks that every class is unchecked, so a later change cannot break them quietly.

Anything that is not a ShopLiteException, such as a NullPointerException, is a bug. The error handler in the next lesson uses exactly this split: known errors get a clear 4xx, everything else a safe 500.

The parents are abstract, so nobody throws a vague new ConflictException(...); the code must pick a specific kind, such as AlreadyExistsException, one of the different 409 cases. Keep the classes in a shared package such as com.shoplite.common, because every feature uses them.

Fix the error

Make the compiler accept it

Each program fails to compile. Pick the replacement for the marked line.

Round 1 of 2

The service must not need a throws clause. Replace line 1.

class ResourceNotFoundException extends Exception {
ResourceNotFoundException(String message) { super(message); }
}
class ProductService {
String findById(long id) {
throw new ResourceNotFoundException("Product " + id + " was not found.");
}
}

Error

ProductService.java:6: error: unreported exception ResourceNotFoundException; must be caught or declared to be thrown

Thrown by services, never built in controllers

Service methods throw the custom exceptions, because the service is where the rules live: it knows a product is missing or a SKU is taken. The controller only calls the service and returns the result.

Java
// Not like this: the controller decides "not found" by itself@GetMapping("/{id}")public ResponseEntity<ProductResponse> getProduct(@PathVariable long id) {    ProductResponse product = productService.findOrNull(id);    if (product == null) {        return ResponseEntity.notFound().build();      // empty 404, rule copied into the controller    }    return ResponseEntity.ok(product);}
  • The rule is now in two places: the service returns null, the controller turns null into 404. Every other caller of the service must remember the same check.
  • Each controller invents its own error reply, which is how the three different shapes of the last lesson appear.
  • A service that throws keeps the rule in one place, and the controller stays one line long.

Example 3 · ProductService.java and ProductController.java: the service throws

Runs in: the errors-lab practice project (Spring Boot 4.1)

ProductService.javaJava
// src/main/java/com/shoplite/lab/product/ProductService.javapackage com.shoplite.lab.product;
import java.math.BigDecimal;import java.util.Map;import java.util.Optional;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
import com.shoplite.lab.common.AlreadyExistsException;import com.shoplite.lab.common.BusinessRuleException;import com.shoplite.lab.common.ResourceNotFoundException;
@Servicepublic class ProductService {
    private static final Set<Long> CATEGORY_IDS = Set.of(1L, 2L, 3L, 4L, 5L, 6L, 7L);
    private final Map<Long, ProductResponse> products = new ConcurrentHashMap<>();    private final AtomicLong nextId = new AtomicLong(16);
    public ProductService() {        save(new ProductResponse(1, "MOB-RN13", "Redmi Note 13 5G", 2, new BigDecimal("17999.00"), 40));        save(new ProductResponse(3, "MOB-IP15", "iPhone 15 128GB", 2, new BigDecimal("69900.00"), 8));        save(new ProductResponse(6, "ACC-AD141", "boAt Airdopes 141", 4, new BigDecimal("1299.00"), 120));    }
    public ProductResponse findById(long id) {        return Optional.ofNullable(products.get(id))                .orElseThrow(() -> new ResourceNotFoundException("Product", id));    }
    public ProductResponse create(CreateProductRequest request) {        if (!CATEGORY_IDS.contains(request.categoryId())) {            throw new BusinessRuleException("Category " + request.categoryId() + " does not exist.");        }        boolean skuTaken = products.values().stream().anyMatch(p -> p.sku().equals(request.sku()));        if (skuTaken) {            throw new AlreadyExistsException("A product with SKU " + request.sku() + " already exists.");        }        int stock = request.stock() == null ? 0 : request.stock();        return save(new ProductResponse(nextId.getAndIncrement(), request.sku(), request.name(),                request.categoryId(), request.price(), stock));    }
    private ProductResponse save(ProductResponse product) {        products.put(product.id(), product);        return product;    }}
// src/main/java/com/shoplite/lab/product/ProductController.javapackage com.shoplite.lab.product;
import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/products")public class ProductController {
    private final ProductService productService;
    public ProductController(ProductService productService) {        this.productService = productService;    }
    @GetMapping("/{id}")    public ProductResponse getProduct(@PathVariable long id) {        return productService.findById(id);          // no null check, no if: the service throws    }
    @PostMapping    @ResponseStatus(HttpStatus.CREATED)    public ProductResponse create(@RequestBody CreateProductRequest request) {        return productService.create(request);    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:05:44 GMT
Connection: close

{"timestamp":"2026-10-16T05:05:44.463Z","status":500,"error":"Internal Server Error","path":"/api/v1/products/99"}

Server console:
2026-10-16T10:35:44.426+05:30 ERROR 10528 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: com.shoplite.lab.common.ResourceNotFoundException: Product 99 was not found.] with root cause

com.shoplite.lab.common.ResourceNotFoundException: Product 99 was not found.
	at com.shoplite.lab.product.ProductService.lambda$findById$0(ProductService.java:32) ~[!/:0.0.1-SNAPSHOT]
	at java.base/java.util.Optional.orElseThrow(Optional.java:403) ~[na:na]
	at com.shoplite.lab.product.ProductService.findById(ProductService.java:32) ~[!/:0.0.1-SNAPSHOT]
	at com.shoplite.lab.product.ProductController.getProduct(ProductController.java:24) ~[!/:0.0.1-SNAPSHOT]
	...

What this code does

  • findById uses orElseThrow(() -> new ResourceNotFoundException("Product", id)); create checks the category first (422) and then the SKU (409). The controller has no if at all.
  • The log now names the real problem: ResourceNotFoundException: Product 99 was not found. But the client still gets 500, because nothing maps the exception to a status yet.
Throwing is only half the job. Until something maps the exception to a status, Spring Boot still answers 500, as Example 3 shows.

@ResponseStatus and ResponseStatusException

@ResponseStatus is an annotation on an exception class that tells Spring MVC which HTTP status to send whenever that exception escapes a controller. ResponseStatusException does the same for a one-off case, with the status in its constructor.

Put @ResponseStatus on the exception classes and the 404, 409 and 422 replies change at once.

Example 4 · @ResponseStatus on the exception classes

Runs in: the errors-lab practice project (Spring Boot 4.1)

ResourceNotFoundException.javaJava
// src/main/java/com/shoplite/lab/common/ResourceNotFoundException.javapackage com.shoplite.lab.common;
import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ResponseStatus;
/** The resource named in the URL does not exist. */@ResponseStatus(HttpStatus.NOT_FOUND)public class ResourceNotFoundException extends ShopLiteException {
    private final String resource;    private final Object id;
    public ResourceNotFoundException(String resource, Object id) {        super(resource + " " + id + " was not found.");        this.resource = resource;        this.id = id;    }
    public String getResource() {        return resource;    }
    public Object getId() {        return id;    }}
// src/main/java/com/shoplite/lab/common/ConflictException.javapackage com.shoplite.lab.common;
import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ResponseStatus;
/** The request clashes with the current state of the data. */@ResponseStatus(HttpStatus.CONFLICT)public abstract class ConflictException extends ShopLiteException {
    protected ConflictException(String message) {        super(message);    }}
// src/main/java/com/shoplite/lab/common/BusinessRuleException.javapackage com.shoplite.lab.common;
import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ResponseStatus;
/** Valid fields that break a rule involving other data, such as an unknown category. */@ResponseStatus(HttpStatus.UNPROCESSABLE_CONTENT)public class BusinessRuleException extends ShopLiteException {
    public BusinessRuleException(String message) {        super(message);    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:10:17 GMT

{"timestamp":"2026-10-16T05:10:17.311Z","status":404,"error":"Not Found","path":"/api/v1/products/99"}

$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"MOB-RN13","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
HTTP/1.1 409
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:10:18 GMT

{"timestamp":"2026-10-16T05:10:18.287Z","status":409,"error":"Conflict","path":"/api/v1/products"}

$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":42,"price":999.00,"stock":30}'
HTTP/1.1 422
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:10:18 GMT

{"timestamp":"2026-10-16T05:10:18.643Z","status":422,"error":"Unprocessable Content","path":"/api/v1/products"}

What this code does

  • The statuses are right now: 404, 409 (the annotation on ConflictException is inherited by AlreadyExistsException) and 422. UNPROCESSABLE_CONTENT is the Spring 7 name for 422.
  • The bodies are still the default four fields, and Product 99 was not found. is nowhere in them. The log stays quiet too: Spring treats these as handled.

Example 5 · ResponseStatusException for a one-off status

Runs in: the errors-lab practice project (Spring Boot 4.1)

CouponController.javaJava
package com.shoplite.lab.coupon;
import java.util.Set;
import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.server.ResponseStatusException;
@RestControllerpublic class CouponController {
    private static final Set<String> EXPIRED = Set.of("FEST20", "DIWALI10");
    @GetMapping("/api/v1/coupons/{code}")    public String check(@PathVariable String code) {        if (EXPIRED.contains(code)) {            // a one-off status for one endpoint, no exception class needed            throw new ResponseStatusException(HttpStatus.GONE, "Coupon " + code + " has expired.");        }        return "Coupon " + code + " is valid";    }}
Sample output
$ curl -i http://localhost:8080/api/v1/coupons/FEST20
HTTP/1.1 410
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 05:10:19 GMT

{"timestamp":"2026-10-16T05:10:19.798Z","status":410,"error":"Gone","path":"/api/v1/coupons/FEST20"}

$ curl -i http://localhost:8080/api/v1/coupons/NEWUSER50
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 25
Date: Fri, 16 Oct 2026 05:10:20 GMT

Coupon NEWUSER50 is valid

What this code does

  • new ResponseStatusException(HttpStatus.GONE, "...") sets 410 Gone for this one case without a new class. It is handy in a quick prototype or a rare endpoint.
  • Its reason text is hidden like any other message, and the status decision now sits in the controller. In ShopLite such a case gets a proper exception thrown by a service.

@ResponseStatus and ResponseStatusException both give the right status code with no handler code at all. The body is still the default one with timestamp, status, error and path, and the message you wrote stays hidden.

Both also tie your service exceptions to HTTP. A service should not need to know about status codes, and the same exception may one day be thrown from a scheduled job with no HTTP request at all. ShopLite therefore uses them only as a first step; the global handler in the next lesson replaces them.

Good messages: what failed and which id

A good exception message is one sentence that a user of the API can read and act on. It says what failed and which value caused it, such as Product 99 was not found.

Compare the messages below: the first two tell the client what failed, the last three are vague or leak internals.

Java
new ResourceNotFoundException("Product", 99);// Product 99 was not found.                         (good: what and which id)
new AlreadyExistsException("A product with SKU " + sku + " already exists.");// A product with SKU MOB-RN13 already exists.        (good: names the clashing value)
new BusinessRuleException("Not found");                        // too vague: what was not found?new BusinessRuleException("SELECT * FROM categories ... 0 rows"); // leaks SQL and table namesnew BusinessRuleException(e.toString());                       // leaks class names and internals
  • Build the message in the exception's constructor, as ResourceNotFoundException("Product", 99) does, so every "not found" reads the same.
  • Keep the values the client may need (an id, a SKU) as fields too, with getters.
  • Never put SQL, table names, server names or stack traces in a message. When you wrap a low-level exception, pass it as the cause; the log shows it, the client does not.

Next step

Check your understanding

12 quick questions