title: How to use Custom Exception for Spring Boot Rest?
body: <p>Am using Spring Boot to connect to MySQL 5 database (via JPA) along with Spring Rest for the server side.</p>
  
  <p>My POJO:</p>
  
  <pre><code>@Entity
  public class Employee {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private long id;
  
      private String firstName;
      private String lastName;
  
      public String getFirstName() {
          return firstName;
      }
  
      public void setFirstName(String firstName) {
          this.firstName = firstName;
      }
  
      public String getLastName() {
          return lastName;
      }
  
      public void setLastName(String lastName) {
          this.lastName = lastName;
      }
  }
  </code></pre>
  
  <p>EmployeRespository:</p>
  
  <pre><code>@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
  public interface EmployeeRepository extends PagingAndSortingRepository&lt;Employee, Long&gt; {
  
      Collection&lt;Employee&gt; findByLastName(@Param("name") String name);
  
  }
  </code></pre>
  
  <p>EmployeeService:</p>
  
  <pre><code>@RestController
  @RequestMapping("/employee")
  public class EmployeeService {
  
      @Autowired
      private EmployeeRepository employeeRepository;
  
      @RequestMapping(value = "/findByLastName?{lastName}=", method = RequestMethod.GET)
      Object getEmployees(@PathVariable String lastName) {
          Collection&lt;Employee&gt; result = this.employeeRepository.findByLastName(lastName);
          if (result == null) {
              throw new EmployeeNotFoundException(lastName);
          }
          return result;
      }
  }
  </code></pre>
  
  <p>EmployeeNotFoundException:</p>
  
  <pre><code>public class EmployeeNotFoundException extends RuntimeException {
  
      private static final long serialVersionUID = 1L;
  
      public EmployeeNotFoundException(String id) {
          super("Could not find Employee " + id);
      }
  }
  </code></pre>
  
  <p>Now when call call my REST API, I get the following results:</p>
  
  <p>This one doesn't exist in my database and the EmployeeNotFoundException is not thrown:</p>
  
  <pre><code>curl -X GET -H "Content-Type:application/json" http://localhost:8080/employee/search/findByLastName?name="Smith"
  </code></pre>
  
  <p>Results in:</p>
  
  <pre><code>{
      "_embedded" : {
          "employee" : [ ]
      },
      "_links" : {
          "self" : {
              "href" : "http://localhost:8080/employee/search/findByLastName?name=Smith"
          }
      }
  }
  </code></pre>
  
  <p>Question(s):</p>
  
  <ol>
  <li><p>Why is my EmployeeNotFoundException being thrown? Is there a better way to implement this (along with perhaps the HTTP Status Code being displayed)?</p></li>
  <li><p>Any URL(s) regarding how to unit test would be great (along with the best unit test libraries)...</p></li>
  </ol>
  
  <p>Thank you for taking the time to read this.</p>