-2

I'm trying to create custom exception using java, i got error when try to throw this exception

I had follow the tutor inside this https://www.baeldung.com/java-new-custom-exception

here is my custom exception

package projectdemo.exception;

import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;

@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends Exception { 
    public RecordNotFoundException(String errorMessage) {
        super(errorMessage);
    }
}

and here is how i throw the exception

package projectdemo.service;

import projectdemo.model.MasterUser;
import projectdemo.classes.Response;
import projectdemo.repository.Repository;
import projectdemo.exception.RecordNotFoundException; //i had try to import this to
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.http.ResponseEntity;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class MasterUserService {
    @Autowired
    private Repository repository;
    
    @Transactional(rollbackFor = Exception.class) 
    public ResponseEntity<Response<MasterUser>> method(Long id) { 

        MasterUser userExitsing = repository.findById(id).orElse(null);
        if(userExitsing == null) throw new RecordNotFoundException("User not found"); //error in this line
        
        
        Response<MasterUser> apiRes = new  Response<userExitsing );
        return new ResponseEntity<Response<MasterUser>>(apiRes, apiRes.status);
    }

}

and this the error i got :

enter image description here

Am I missing something??

I would be glad for any help.

Hansen
  • 650
  • 1
  • 11
  • 32

1 Answers1

1

RecordNotFoundException extends Exception and, therefore, is a checked exception.

You have to declare the exception in the method signature:

@Transactional(rollbackFor = Exception.class) 
public ResponseEntity<Response<MasterUser>> method(Long id) throws RecordNotFoundException { 

    MasterUser userExitsing = repository.findById(id).orElse(null);
    if(userExitsing == null) throw new RecordNotFoundException("User not found"); //error in this line
    
    
    Response<MasterUser> apiRes = new  Response<userExitsing );
    return new ResponseEntity<Response<MasterUser>>(apiRes, apiRes.status);
}

Alternatively, you could make it a RuntimeExcpetion. Then you don't have to declare it, plus you can remove the rollbackFor attribute in the Transactional annotation.

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82