Database Exceptions Are Unchecked In Scaffolded Controllers
- Dominant language
- Groovy
- Stars
- 2.9k
- Forks
- 975
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 92
Description
### Steps to Reproduce
1. create a domain (domain1) that is empty
2. create another domain (domain2) that has a field Domain1 domain1 as a one-to-one relationship
3. create controllers for the domains with static scaffold = Domain1 / Domain2
4. start the application
5. create an instance of domain1 (object1)
6. create an instance of domain2 that references object1
7. delete object1
### Expected Behaviour
The application should give an error message that the object cannot be deleted due to the violated foreign key constraint.
### Actual Behaviour
The application prints a whole stack trace, which would only be helpful for developers but not for normal users
### How It Can Be Fixed
By surrounding the method call `delete()` with a try-catch block in the Controller-Template the problem would be fixed:
```
import org.springframework.dao.DataIntegrityViolationException
...
def delete(${className} ${propertyName}) {
...
try {
${propertyName}.delete(flush: true)
flash.message = message(code: 'default.deleted.message', args: [message(code: '${propertyName}.label', default: '${className}'), params.id])
redirect(action: "index")
}catch (DataIntegrityViolationException e) {
flash.message = message(code: 'default.not.deleted.message', args: [message(code: '${propertyName}.label', default: '${className}'), params.id])
redirect(action: "show", id: params.id)
}
}
```
### Environment Information
- **Operating System**: Ubuntu
- **Grails Version:** 3.1.7
- **JDK Version:** 1.7
### Example Application
See [attachment](https://github.com/grails3-plugins/scaffolding/files/284477/ForeignKeyViolationExample.zip)
Contributor guide
Research direction
Start by locating the scaffolded controller template and its delete() method, then inspect how database exceptions are currently handled. Verify the generated controller behavior for a one-to-one foreign-key deletion using the linked reproduction steps; done means users receive a friendly deletion error instead of a stack trace.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- groovy
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100