<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Zer</title>
    <description>The latest articles on Forem by Zer (@zerabsin).</description>
    <link>https://forem.com/zerabsin</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1141843%2F1eea6801-2867-4dcb-a427-f5dea8c06f3e.png</url>
      <title>Forem: Zer</title>
      <link>https://forem.com/zerabsin</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/zerabsin"/>
    <language>en</language>
    <item>
      <title>Spring Boot REST Basics : How to validate your request body</title>
      <dc:creator>Zer</dc:creator>
      <pubDate>Sat, 23 Sep 2023 23:57:14 +0000</pubDate>
      <link>https://forem.com/zerabsin/spring-boot-rest-basics-how-to-validate-your-request-body-3n81</link>
      <guid>https://forem.com/zerabsin/spring-boot-rest-basics-how-to-validate-your-request-body-3n81</guid>
      <description>&lt;h2&gt;
  
  
  Overview
&lt;/h2&gt;

&lt;p&gt;In software development, it is important to do some validation for security purposes and also lessen the unexpected errors, but it takes a lot of hours just to implement specific validation methods. In this post, I will share the easiest way on how to validate your request body in Spring Boot. &lt;/p&gt;

&lt;h2&gt;
  
  
  Let's get started
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Add dependency
&lt;/h3&gt;

&lt;p&gt;Add the spring boot starter validation to your project. You can do this by adding the code below to your &lt;code&gt;pom.xml&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;             
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-validation&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Update your controller
&lt;/h3&gt;

&lt;p&gt;Let's say you have a login API that authenticates the user. All you need to do is add the &lt;code&gt;@Valid&lt;/code&gt; annotation to your request body. For this example I added the &lt;code&gt;@Valid&lt;/code&gt; annotation to my &lt;code&gt;userLoginRequestModel&lt;/code&gt;. This signals Spring Boot to do some validation of the model.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @PostMapping("/login")
    public UserLoginResponseModel login(@Valid @RequestBody UserLoginRequestModel userLoginRequestModel) {
        return userService.login(userLoginRequestModel);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Update your model
&lt;/h3&gt;

&lt;p&gt;In your model, all you need to add is the specific validation annotation that we want to implement. For this example, I used the &lt;code&gt;@NotEmpty&lt;/code&gt; annotation to make sure the username and password is required. I also added the message parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class UserLoginRequestModel {
    @NotEmpty(message = "Username is required.")
    private String username;

    @NotEmpty(message = "Password is required.")
    private String password;

    //...
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are a lot of validations you can use, such as &lt;code&gt;@Min&lt;/code&gt; and &lt;code&gt;@Max&lt;/code&gt;, make sure to check the documentation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Update your exception handler
&lt;/h3&gt;

&lt;p&gt;To display the validation results, It is better to handle the error in your exception handler method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map&amp;lt;String, String&amp;gt; handleValidationExceptions(
  MethodArgumentNotValidException ex) {
    Map&amp;lt;String, String&amp;gt; errors = new HashMap&amp;lt;&amp;gt;();
    ex.getBindingResult().getAllErrors().forEach((error) -&amp;gt; {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    return errors;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Test
&lt;/h3&gt;

&lt;p&gt;Now, try to test the validation in your API. The result should return something like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "Username is required.",
  "Password is required."
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Spring Boot makes it way easier to do validation just by using the &lt;code&gt;@Valid&lt;/code&gt;annotation. No need to implement validation methods that sometimes may not work. So make sure to try this out.&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>restapi</category>
    </item>
    <item>
      <title>Spring Boot REST Basics : Create Custom Exceptions with @ControllerAdvice annotation</title>
      <dc:creator>Zer</dc:creator>
      <pubDate>Wed, 20 Sep 2023 14:03:34 +0000</pubDate>
      <link>https://forem.com/zerabsin/spring-boot-rest-basics-create-custom-exceptions-with-controlleradvice-annotation-1o5g</link>
      <guid>https://forem.com/zerabsin/spring-boot-rest-basics-create-custom-exceptions-with-controlleradvice-annotation-1o5g</guid>
      <description>&lt;h2&gt;
  
  
  Overview
&lt;/h2&gt;

&lt;p&gt;In this post, I will share my experience in creating custom exceptions with &lt;code&gt;@ControllerAdvice&lt;/code&gt; annotation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Basic Spring boot knowledge&lt;/li&gt;
&lt;li&gt;Basic REST API / Web Dev knowledge&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Custom Exceptions
&lt;/h3&gt;

&lt;p&gt;In Java, we can create our own type of exception that is tailored to our business logic. Custom exceptions give us the flexibility to add more information to our exceptions and to handle errors in a different way.&lt;/p&gt;

&lt;h3&gt;
  
  
  ControllerAdvice annotation
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;@ControllerAdvice&lt;/code&gt; is an annotation that allows us to handle exceptions globally in one file. So we can just create one class and define the actions or methods that will be triggered every time an exception is thrown.&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's get started
&lt;/h2&gt;

&lt;p&gt;In this example, I want to create a custom exception that will handle login errors and return a &lt;code&gt;401 Unauthorized Error&lt;/code&gt; HTTP response to the client.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Create your own custom exception
&lt;/h3&gt;

&lt;p&gt;In creating your own custom exception, you have to make sure that your custom exception class is a child of &lt;code&gt;Exception&lt;/code&gt; class (checked) or &lt;code&gt;RuntimeException&lt;/code&gt; class (unchecked).&lt;/p&gt;

&lt;p&gt;I created my own custom exception called &lt;code&gt;CustomInvalidLoginException.java&lt;/code&gt; and extend the &lt;code&gt;RuntimeException&lt;/code&gt; class.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CustomInvalidLoginException extends RuntimeException {
    public CustomInvalidLoginException() {
        super("INVALID LOGIN");
    }

    public CustomInvalidLoginException(String message) {
        super(message);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Create your own global exception handler
&lt;/h3&gt;

&lt;p&gt;In my project, I created a class called &lt;code&gt;GlobalExceptionHandler.java&lt;/code&gt; and annotate it with &lt;code&gt;@ControllerAdvice&lt;/code&gt; to let Spring boot know this is a global exception handler class. &lt;/p&gt;

&lt;p&gt;Inside the class, I created a method that will handle the invalid login exception and annotate it with &lt;code&gt;@ExceptionHandler(CustomInvalidLoginException.class)&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(CustomInvalidLoginException.class)
    public ResponseEntity&amp;lt;Object&amp;gt; handleInvalidLogin() {
        return new ResponseEntity&amp;lt;&amp;gt;("INVALID LOGIN", new HttpHeaders(), HttpStatus.UNAUTHORIZED);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For this exception, I will just return &lt;code&gt;401 HTTP status&lt;/code&gt; to the user.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Test
&lt;/h3&gt;

&lt;p&gt;Lastly, all you need to do is throw the custom error in your business logic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
else {
     throw new CustomInvalidLoginException();
}
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Spring boot makes it easier for us to manage exceptions just by using these annotations: &lt;code&gt;@ControllerAdvice&lt;/code&gt; and &lt;code&gt;@ExceptionHandler&lt;/code&gt;. In my opinion, this improves the readability and maintainability of your application because you can handle your exceptions in just one file!&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>beginners</category>
      <category>restapi</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
