簡體   English   中英

如何在Spring Boot Rest中使用自定義異常?

[英]How to use Custom Exception for Spring Boot Rest?

我使用Spring Boot連接到MySQL 5數據庫(通過JPA)以及服務器端的Spring Rest。

我的POJO:

@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;
    }
}

EmployeRespository:

@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> {

    Collection<Employee> findByLastName(@Param("name") String name);

}

的EmployeeService:

@RestController
@RequestMapping("/employee")
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @RequestMapping(value = "/findByLastName?{lastName}=", method = RequestMethod.GET)
    Object getEmployees(@PathVariable String lastName) {
        Collection<Employee> result = this.employeeRepository.findByLastName(lastName);
        if (result == null) {
            throw new EmployeeNotFoundException(lastName);
        }
        return result;
    }
}

EmployeeNotFoundException:

public class EmployeeNotFoundException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public EmployeeNotFoundException(String id) {
        super("Could not find Employee " + id);
    }
}

現在,當調用我的REST API時,我得到以下結果:

這個在我的數據庫中不存在,並且不會拋出EmployeeNotFoundException:

curl -X GET -H "Content-Type:application/json" http://localhost:8080/employee/search/findByLastName?name="Smith"

結果是:

{
    "_embedded" : {
        "employee" : [ ]
    },
    "_links" : {
        "self" : {
            "href" : "http://localhost:8080/employee/search/findByLastName?name=Smith"
        }
    }
}

問題(S):

  1. 為什么拋出我的EmployeeNotFoundException? 有沒有更好的方法來實現它(以及可能顯示的HTTP狀態代碼)?

  2. 任何關於如何進行單元測試的URL都會很棒(以及最好的單元測試庫)......

感謝您抽出時間來閱讀。

這是因為,以下行不返回null,而是一個空列表。

Collection<Employee> result = this.employeeRepository.findByLastName(lastName);

您也可以檢查空列表以及拋出異常,或者只返回空列表。 我不建議為查找/搜索拋出異常。 我個人,拋出任何NotFoundException只為get方法一樣getById 否則我只返回空列表。

if (result == null || result.isEmpty()) {
    throw new EmployeeNotFoundException(lastName);
}

此外,修改Hey-men-wattsup的代碼以發送錯誤代碼,而不是在Controller中拋出異常。 這將發送404,NotFound代碼。

@ExceptionHandler(EmployeeNotFoundException.class)
    public void handleException(EmployeeNotFoundException  e, , HttpServletResponse response) {
    response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
}

Spring Boot Test的MockMvc類與Mockito相結合,提供了對控制器進行單元測試所需的方法。

如果您想知道EmployeeNotFoundException ,它會被拋出但不被處理。 您至少需要一個@ExceptionHandler注釋方法來處理它。

 @ExceptionHandler(EmployeeNotFoundException.class)
        public void handleException(EmployeeNotFoundException  e) {
        // do something
        }

像這樣:

 @RestController
    @RequestMapping("/employee")
    public class EmployeeService {

        @Autowired
        private EmployeeRepository employeeRepository;

        @RequestMapping(value = "/findByLastName?{lastName}=", method = RequestMethod.GET)
        Object getEmployees(@PathVariable String lastName) {
            Collection<Employee> result = this.employeeRepository.findByLastName(lastName);
            if (result == null) {
                throw new EmployeeNotFoundException(lastName);
            }
            return result;
        }

       @ExceptionHandler(EmployeeNotFoundException.class)
        public void handleException(EmployeeNotFoundException  e) {
         System.out.println("Exception triggered");
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM