简体   繁体   中英

Throwing the status exception

I have a core module that has such relationships

compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-mail')

in service in method I would like to throw an exception (or otherwise) from the status code (for example, NOT FOUND 404) in case the user is not found.

getById(Long id) {
     //if the user with specified id does not exist

     //for example, cast an exception throw new UserNotFoundException(new List<FieldError>); with a list of error fields
    }

the problem is that this module has no dependency

compile('org.springframework.boot:spring-boot-starter-web')

and cannot use objects such as ResponseEntity or HttpStatus .

I want to achieve a result such as that here https://github.com/JonkiPro/REST-Web-Services/blob/master/src/main/java/com/service/app/rest/controller/advice/ErrorFieldsExceptionHandler.java , but without org.springframework.web .

I could be advised on how I can throw an exception with the status and error list object as response?

Let's exercise the good old Single Responsibility Principle .

The Service layer is not concerned about HTTP STATUS. Throwing some sort of HttpStatus404Exception from the Service layer is not a good choice. How about if someone wants to use the Service layer in a batch processor which connects directly to the database? In this case the HttpStatus404Exception is totally out of place.

Throw a UserNotFoundException (which could extend a NotFoundException ) and let the Controller layer (in your case a WebController layer) handle the exceptions gracefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM