SpringBoot抛出JpaSystemException而不是ClientException

时间:2018-06-13 16:29:12

标签: spring-boot exception spring-data-jpa

当方法JpaSystemException投掷ClientException时,为什么SpringBoot会抛出handleException() ClientException

@RestController
@RequestMapping(path = "/api/clients")
public class ClientController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MessageByLocaleService messageByLocaleService;

    @Autowired
    private PersonService personService;

    @PostMapping(path = "/saveperson", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> savePerson(@RequestBody @Valid Person person) throws Exception {
        try {
            this.personService.save(person);
        }catch(ClientException ce){
            logger.info(ce.getMessage());
        }catch(JpaSystemException jse){
            logger.info(jse.getMessage());  // <<<<< is catching this exception instead ClientException
        }catch (Exception e){
            logger.info(e.getMessage());
        }
        return new ResponseEntity<Void>(HttpStatus.CREATED);
    }
}

@Service
@Transactional
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private MessageByLocaleService messageByLocaleService;

    @Override
    public Person save(Person client) throws ClientException {
        try {
            return this.personRepository.save(client); //trying to save the client throw a MySQLIntegrityConstraintViolationException: Duplicate entry..
        } catch (DataIntegrityViolationException dive) {
            Throwable th = dive.getCause();
            if (th != null && th instanceof ConstraintViolationException) {

                ConstraintViolationException violationException = (ConstraintViolationException) th;
                violationException.printStackTrace();

                handleException(dive, violationException); 

            }
        }
        return null;
    }

    private void handleException(DataIntegrityViolationException dive, ConstraintViolationException violationException) throws ClientException {
        try {
            String ukName = violationException.getConstraintName();
            String ukMessage = messageByLocaleService.getMessage(ukName);

            if (ukMessage != null) {
                ClientException ce = new ClientException(dive.getMostSpecificCause().getMessage(), ukMessage);
                throw ce; 
            }

        } catch (NoSuchMessageException ex) {
            throw new ClientException(violationException.getCause().getMessage(), "UnknownError : " + violationException.getCause().getMessage());
        }
    }   
}

0 个答案:

没有答案