[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"global-header-tutorials-static":3,"article-global-exception-handling-in-spring-boot":4,"initial-similar-fetch":22},[],{"alias":5,"title":6,"description":7,"content":8,"thumbnail":9,"keywords":10,"categories":17,"tags":20,"createdAt":21},"global-exception-handling-in-spring-boot","Implementing Robust Global Exception Handling in Spring Boot","How to Handle Errors in Spring Boot: An Architectural Guide","{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"While working on a Spring Framework project, handling exceptions is crucial. When something goes wrong in the code, Java throws an exception. If we don't handle it properly, the stack trace text will be shown to the user. This might be unprofessional and might leak security to the users.\"}]},{\"type\":\"heading\",\"attrs\":{\"textAlign\":null,\"level\":2},\"content\":[{\"type\":\"text\",\"text\":\"How Error Handling Works\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"Instead of handling exceptions inside every method of the code, Spring Boot provides a mechanism to build global exception handling.\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"Let's assume the security guard is standing at the exit of our application. No matter where the exception or error happens in any part of the code, it will throw to the guard, who then turns it into a readable message before sending it to the users.\"}]},{\"type\":\"heading\",\"attrs\":{\"textAlign\":null,\"level\":2},\"content\":[{\"type\":\"text\",\"text\":\"Core Architecture\"}]},{\"type\":\"image\",\"attrs\":{\"src\":\"https:\u002F\u002Fapi.csbyte.com\u002Fuploads\u002Feditor\u002F554489e1-d142-4ea5-a393-994a13d7b113_exception-handling.png\",\"alt\":null,\"title\":null,\"width\":null,\"height\":null}},{\"type\":\"heading\",\"attrs\":{\"textAlign\":null,\"level\":2},\"content\":[{\"type\":\"text\",\"text\":\"Error Message Formatting\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"When the errors occur in our application, we need to format them and send a readable message to the users.\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"Let's create the utility class for this. \"}]},{\"type\":\"codeBlock\",\"attrs\":{\"language\":\"java\"},\"content\":[{\"type\":\"text\",\"text\":\"package com.csbyte.exceptions;\\n\\n\\nimport lombok.AllArgsConstructor;\\nimport lombok.Builder;\\nimport lombok.Data;\\nimport lombok.NoArgsConstructor;\\n\\nimport java.time.Instant;\\nimport java.util.HashMap;\\nimport java.util.Map;\\n\\n@Data\\n@Builder\\n@NoArgsConstructor\\n@AllArgsConstructor\\npublic class Error {\\n\\n    private static final long serialVersionUID = 1L;\\n    \u002F**\\n     * HTTP status code set by the origin server.\\n     *\u002F\\n    private Integer code;\\n\\n    \u002F**\\n     * Error message.\\n     *\u002F\\n    private String message;\\n\\n    \u002F**\\n     * Url of request that produced the error.\\n     *\u002F\\n    private String url = \\\"Not available\\\";\\n\\n    \u002F**\\n     * Method of request that produced the error.\\n     *\u002F\\n    private String reqMethod = \\\"Not available\\\";\\n\\n    \u002F**\\n     * Timestamp\\n     *\u002F\\n    private Instant timestamp;\\n\\n    Map\u003CString, String> errors = new HashMap\u003C>();\\n}\\n\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"We are using Lambok to get rid of setter and getter methods boilerplate code. We can use the Java record as well. This class defines the simple response for errors.\"}]},{\"type\":\"heading\",\"attrs\":{\"textAlign\":null,\"level\":2},\"content\":[{\"type\":\"text\",\"text\":\"Creating a Helper Utility\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"To create code clean and reduce the boilerplate code, we will create a utils class that builds the error response.\"}]},{\"type\":\"codeBlock\",\"attrs\":{\"language\":\"java\"},\"content\":[{\"type\":\"text\",\"text\":\"package com.csbyte.exceptions;\\n\\nimport jakarta.servlet.http.HttpServletRequest;\\n\\nimport java.time.Instant;\\n\\npublic class ErrorUtils {\\n\\n  public static Error createError(HttpServletRequest request, String message, Integer code) {\\n    return Error.builder()\\n            .code(code)\\n            .message(message)\\n            .reqMethod(request.getMethod())\\n            .url(request.getRequestURL().toString())\\n            .timestamp(Instant.now())\\n            .build();\\n  }\\n\\n}\"}]},{\"type\":\"heading\",\"attrs\":{\"textAlign\":null,\"level\":2},\"content\":[{\"type\":\"text\",\"text\":\"Creating Custom Errors \"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"Instead of throwing a generic \"},{\"type\":\"text\",\"marks\":[{\"type\":\"code\"}],\"text\":\"RuntimeException\"},{\"type\":\"text\",\"text\":\" exception, it's best practice to create some custom exceptions that might be used in the code to throw application custom errors. \"}]},{\"type\":\"codeBlock\",\"attrs\":{\"language\":\"java\"},\"content\":[{\"type\":\"text\",\"text\":\"package com.csbyte.exceptions;\\n\\npublic class DataNotFoundException extends RuntimeException {\\n\\n    private static final long serialVersionUID = 1L;\\n\\n    String field;\\n    String fieldName;\\n    Long fieldId;\\n\\n    public DataNotFoundException(String fieldName, String field, Long fieldId) {\\n        super(String.format(\\\"%s not found with %s: %d\\\", fieldName, field, fieldId));\\n        this.fieldName = fieldName;\\n        this.field = field;\\n        this.fieldId = fieldId;\\n    }\\n}\\n\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"If the app tries to query the items in the database that don't exist, we can use this exception to capture exactly what went missing.\"}]},{\"type\":\"codeBlock\",\"attrs\":{\"language\":\"java\"},\"content\":[{\"type\":\"text\",\"text\":\"package com.csbyte.exceptions;\\n\\nimport java.io.Serial;\\n\\npublic class APIException extends RuntimeException {\\n\\n    @Serial\\n    private static final long serialVersionUID = 1L;\\n\\n    public APIException() {\\n    }\\n\\n    public APIException(String message) {\\n        super(message);\\n    }\\n}\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"This is the generic simple  bad request api exception. If a user tries to do something invalid, we can throw this exception.\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"You can create the desired exception in accordance with the application requirement.\"}]},{\"type\":\"heading\",\"attrs\":{\"textAlign\":null,\"level\":2},\"content\":[{\"type\":\"text\",\"text\":\"Creating Global Exception Handling\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"Spring provides a clean way to handle exceptions globally using \"},{\"type\":\"text\",\"marks\":[{\"type\":\"code\"}],\"text\":\"ControllerAdvice\"},{\"type\":\"text\",\"text\":\"  annotations. We are using \"},{\"type\":\"text\",\"marks\":[{\"type\":\"code\"}],\"text\":\"RestControllerAdvice\"},{\"type\":\"text\",\"text\":\" a  user for rest api services.\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"Let's create a class that will handle multiple exceptions.\"}]},{\"type\":\"codeBlock\",\"attrs\":{\"language\":\"java\"},\"content\":[{\"type\":\"text\",\"text\":\"package com.csbyte.exceptions;\\n\\nimport jakarta.servlet.http.HttpServletRequest;\\nimport org.springframework.http.HttpStatus;\\nimport org.springframework.http.ResponseEntity;\\nimport org.springframework.validation.FieldError;\\nimport org.springframework.web.bind.MethodArgumentNotValidException;\\nimport org.springframework.web.bind.annotation.ExceptionHandler;\\nimport org.springframework.web.bind.annotation.RestControllerAdvice;\\n\\nimport java.util.HashMap;\\nimport java.util.Map;\\n\\n\\n@RestControllerAdvice\\npublic class GlobalExceptionHandler {\\n\\n\\t@ExceptionHandler(APIException.class)\\n\\tpublic ResponseEntity\u003CError> apiException(HttpServletRequest request, APIException e) {\\n\\t\\tString message = e.getMessage();\\n\\t\\tError error = ErrorUtils.createError(request, message, HttpStatus.BAD_REQUEST.value());\\n\\t\\treturn new ResponseEntity\u003C>(error, HttpStatus.BAD_REQUEST);\\n\\t}\\n\\n\\n\\t@ExceptionHandler(DataNotFoundException.class)\\n\\tpublic ResponseEntity\u003CError> dataNotFoundException(HttpServletRequest request, DataNotFoundException e) {\\n\\t\\tString message = e.getMessage();\\n\\t\\tError error = ErrorUtils.createError(request, message, HttpStatus.NOT_FOUND.value());\\n\\t\\treturn new ResponseEntity\u003C>(error, HttpStatus.NOT_FOUND);\\n\\t}\\n\\n\\n\\t@ExceptionHandler(MethodArgumentNotValidException.class)\\n\\tpublic ResponseEntity\u003CError> handleValidationExceptions(HttpServletRequest request, MethodArgumentNotValidException e) {\\n\\t\\tMap\u003CString, String> errors = new HashMap\u003C>();\\n\\t\\te.getBindingResult().getAllErrors().forEach((error) -> {\\n\\t\\t\\tString fieldName = ((FieldError) error).getField();\\n\\t\\t\\tString errorMessage = error.getDefaultMessage();\\n\\t\\t\\terrors.put(fieldName, errorMessage);\\n\\t\\t});\\n\\t\\tError error = ErrorUtils.createError(request, \\\"Field Validation failed\\\", HttpStatus.BAD_REQUEST.value());\\n\\t\\terror.errors = errors;\\n\\t\\treturn new ResponseEntity\u003C>(error, HttpStatus.BAD_REQUEST);\\n\\t}\\n}\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"The \"},{\"type\":\"text\",\"marks\":[{\"type\":\"code\"}],\"text\":\"GlobalExceptionHandler\"},{\"type\":\"text\",\"text\":\" class is responsible for handling various exceptions that may occur during API requests and providing appropriate responses. It uses Spring's exception handling mechanisms to customize error responses for different types of exceptions.\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"We are using the \"},{\"type\":\"text\",\"marks\":[{\"type\":\"code\"}],\"text\":\"ErrorUtils\"},{\"type\":\"text\",\"text\":\" class to format the error message that was created previously. Let's look into the one exception handling.\"}]},{\"type\":\"codeBlock\",\"attrs\":{\"language\":\"java\"},\"content\":[{\"type\":\"text\",\"text\":\"\\t@ExceptionHandler(MethodArgumentNotValidException.class)\\n\\tpublic ResponseEntity\u003CError> handleValidationExceptions(HttpServletRequest request, MethodArgumentNotValidException e) {\\n\\t\\tMap\u003CString, String> errors = new HashMap\u003C>();\\n\\t\\te.getBindingResult().getAllErrors().forEach((error) -> {\\n\\t\\t\\tString fieldName = ((FieldError) error).getField();\\n\\t\\t\\tString errorMessage = error.getDefaultMessage();\\n\\t\\t\\terrors.put(fieldName, errorMessage);\\n\\t\\t});\\n\\t\\tError error = ErrorUtils.createError(request, \\\"Field Validation failed\\\", HttpStatus.BAD_REQUEST.value());\\n\\t\\terror.errors = errors;\\n\\t\\treturn new ResponseEntity\u003C>(error, HttpStatus.BAD_REQUEST);\\n\\t}\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"Here, when the incoming request fails due to validation, such as (e.g, @NotNull, @Size), Spring throws \"},{\"type\":\"text\",\"marks\":[{\"type\":\"code\"}],\"text\":\"MethodArgumentNotValidException\"},{\"type\":\"text\",\"text\":\" an exception  which is then caught by this handler. This handler intercepts it, loops through the errors, extracts the faulty property field alongside its default constraint message, and injects the map cleanly into the \"},{\"type\":\"text\",\"marks\":[{\"type\":\"code\"}],\"text\":\"Error\"},{\"type\":\"text\",\"text\":\" object response payload.\"}]},{\"type\":\"heading\",\"attrs\":{\"textAlign\":null,\"level\":2},\"content\":[{\"type\":\"text\",\"text\":\"Sample Implementation\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"Let's look at the sample example that throws a custom exception if the article data is not found in the database.\"}]},{\"type\":\"codeBlock\",\"attrs\":{\"language\":\"java\"},\"content\":[{\"type\":\"text\",\"text\":\"    public ArticleResponse updateArticle(Long id, ArticleRequest request) {\\n\\n        ArticleEntity article = articleRepository.findById(id)\\n                .orElseThrow(() -> new DataNotFoundException(\\\"Article not found\\\", \\\"id\\\",           id));\\n        ----------------\\n    }\"}]},{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":null},\"content\":[{\"type\":\"text\",\"text\":\"In this way, by combining Spring Boot \"},{\"type\":\"text\",\"marks\":[{\"type\":\"code\"}],\"text\":\"@RestControllerAdvice\"},{\"type\":\"text\",\"text\":\"  with a custom exception, we can easily handle the exception in the application.\"}]}]}","https:\u002F\u002Fapi.csbyte.com\u002Fuploads\u002Feditor\u002F554489e1-d142-4ea5-a393-994a13d7b113_exception-handling.png",[11,12,13,14,15,16],"coding","spring-boot","spring-framework-7","spring-boot-4","programming","spring",[18,19],"Spring Framework","Spring Boot",[16,12],"2026-06-12T17:15:16.253Z",[23,30,36,42,48,54,60,66,71,77,83,89],{"alias":24,"title":25,"description":26,"thumbnail":27,"createdAt":28,"tutorialAlias":29,"lessonAlias":29},"spring-boot-multi-stage-build-with-docker","Creating spring boot multi-stage build with docker","How to create a Spring Boot multi-stage build with Docker","\u002Fuploads\u002Fthumbnails\u002F8931e2f7-a669-4fbb-855b-5ebe396f462e_multi-stage-build-docke.jpeg","2026-06-20T06:34:41.356Z",null,{"alias":31,"title":32,"description":33,"thumbnail":34,"createdAt":35,"tutorialAlias":29,"lessonAlias":29},"configure-profile-in-spring-boot","Configure different spring profiles in spring boot application","Managing Spring Boot profiles for different environments along with Docker","\u002Fuploads\u002Fthumbnails\u002F59a52e59-4b56-469d-8902-41af5e0f13dd_Spring-profil.jpeg","2026-06-20T04:51:27.098Z",{"alias":37,"title":38,"description":39,"thumbnail":40,"createdAt":41,"tutorialAlias":29,"lessonAlias":29},"spring-boot-create-libraries-gradle","Building Reusable Spring Boot Libraries with Gradle","Architectural Guide: Building Reusable Spring Boot Libraries with Gradle","https:\u002F\u002Fapi.csbyte.com\u002Fuploads\u002Feditor\u002Ff4fb088d-1018-4d2b-ae6c-cdd5d0fd60ae_spring-Initializr.png","2026-06-12T15:55:20.994Z",{"alias":43,"title":44,"description":45,"thumbnail":46,"createdAt":47,"tutorialAlias":29,"lessonAlias":29},"multi-build-project-gradle-spring-boot","Setting up a multi-project build in Gradle for Spring Boot","How to set up a multi-project build in Gradle for Spring Boot","https:\u002F\u002Fapi.csbyte.com\u002Fuploads\u002Feditor\u002Fd43933e4-a7a3-404b-a300-8f02db98f549_multi-build-project.png","2026-06-12T04:15:23.045Z",{"alias":49,"title":50,"description":51,"thumbnail":52,"createdAt":53,"tutorialAlias":29,"lessonAlias":29},"java-version-mismatch-gradle","Java Version Mismatch for Gradle Build","How to Fix Gradle Error: Dependency requires at least JVM runtime version 17. This build uses a Java 8 JVM","\u002Fuploads\u002Fthumbnails\u002Fa4c6c910-5623-4db9-93f5-a515135adb99_gradle_version_mismatc.jpeg","2026-06-09T12:15:21.729Z",{"alias":55,"title":56,"description":57,"thumbnail":58,"createdAt":59,"tutorialAlias":29,"lessonAlias":29},"constructor-confusion-in-spring","Constructor Confusion in Spring Framework","Constructor Confusion and how to handle it in Spring Framework","\u002Fuploads\u002Fthumbnails\u002Fd0f09fc0-e1f9-49d1-bf9a-7d1c41050196_di_confusio.jpeg","2026-05-21T14:13:31.437Z",{"alias":61,"title":62,"description":63,"thumbnail":64,"createdAt":65,"tutorialAlias":29,"lessonAlias":29},"dependency-pull-lookup-spring","Dependency Pull and Contextualized Dependency Lookup in Spring Framework","Dependency Pull and Contextualized Dependency Lookup IoC Types in Spring Framework","\u002Fuploads\u002Fthumbnails\u002Fd1132443-313b-4dce-b713-55f356ef6051_depndency_pull.png","2026-05-20T15:26:06.494Z",{"alias":67,"title":68,"description":68,"thumbnail":69,"createdAt":70,"tutorialAlias":29,"lessonAlias":29},"types-of-dependency-injection-spring","Types of Dependency Injection in Spring Framework","\u002Fuploads\u002Fthumbnails\u002Fafb32399-6dda-41c4-b07c-7decb8257bbb_di_constructor_sette.jpeg","2026-05-19T17:01:51.972Z",{"alias":72,"title":73,"description":74,"thumbnail":75,"createdAt":76,"tutorialAlias":29,"lessonAlias":29},"spring-framework-project-for-gradle-with-intellij-idea","How to create a clean Spring Framework project for Gradle with IntelliJ IDEA","Create a clean Spring Framework project for Gradle with IntelliJ IDEA","https:\u002F\u002Fapi.csbyte.com\u002Fuploads\u002Feditor\u002F0e4abad5-17e2-4311-8cf0-7d8f67af975a_spring-framework.png","2026-05-19T10:28:20.866Z",{"alias":78,"title":79,"description":80,"thumbnail":81,"createdAt":82,"tutorialAlias":29,"lessonAlias":29},"spring-dependency-injection-and-inversion-control","Dependency Injection (DI) and Inversion of Control (IoC) in Spring","Mastering Dependency Injection (DI) and Inversion of Control (IoC) in Spring: A Practical Guide for Building a Notification System","\u002Fuploads\u002Fthumbnails\u002F53c64b94-f188-40b4-9ae9-ad97612d688b_spring_d.jpeg","2026-05-19T05:31:45.138Z",{"alias":84,"title":85,"description":86,"thumbnail":87,"createdAt":88,"tutorialAlias":29,"lessonAlias":29},"setting-nginx-ssl-for-spring-boot-application","Setup Nginx and SSL for Spring Boot Application","Setting Nginx as a reverse proxy in our Spring Boot application","\u002Fuploads\u002Fthumbnails\u002F5433c987-9e86-4d90-9cce-a831d1598ba4_spring-boot-nginx.png","2026-05-04T05:36:23.075Z",{"alias":90,"title":91,"description":92,"thumbnail":93,"createdAt":94,"tutorialAlias":29,"lessonAlias":29},"deploy-spring-boot-application-with-docker","Deploy Spring Boot Application with Docker on Ubuntu Server","The ultimate guide to deploying our Spring Boot application with Docker on an Ubuntu server","https:\u002F\u002Fapi.csbyte.com\u002Fuploads\u002Feditor\u002F55a11844-d1e9-4e83-80e5-c6bb6df7d58b_intellij-idea-build.png","2026-05-03T05:58:55.642Z"]